const express = require('express');
const app = express();
app.use('/', anyroute);
// in anyroute file
router.route('/:id').get(controlFunction)
controlFunction(req, res, res)=> {
// Here we can get the "id" from the variable with req.param.id
}
但是我想在进入控制器功能之前使用“ id”。像这样
modifyFunction(userId)=> {
// Do something with the userId
}
router.route('/:id').get(modifyFunction(id), controlFunction)
在表达请求和JavaScript之前,是否有可能从url
中检索“ id”并在进入请求之前在modifyFunction(id)
中使用。
在一个明确的中间件中,req和res变量从一个中间件传输到下一个中间件。但是我创建了一个函数function(type,id),该函数返回了一个中间件函数(req,res,next)。在此函数(类型,ID)中,类型参数将手动传递,并从URL中传递ID。
router
.route('/all-contacts/:id')
.get(authController.isLoggedIn, viewController.getAxiosConfig('contactNameEmail', id), viewController.getAllContact);
exports.getAxiosConfig = (type, id) => {
return (req, res, next) => {
const config = axiosConfig(type, id);
const accessToken = req.cookies.access_token;
const tokenArray = config.headers.Authorization.split(' ');
tokenArray.splice(1, 1, accessToken);
const newToken = tokenArray.join(' ');
config.headers.Authorization = newToken;
req.config = config;
next();
};
};
exports.getAllContact = catchAsync(async (req, res, next) => {
// const token = req.cookies.access_token;
// console.log(token);
// const config = axiosConfig('contactNameEmail');
req.config.method = 'GET';
// const tokenArray = config.headers.Authorization.split(' ');
// tokenArray.splice(1, 1, token);
// const newToken = tokenArray.join(' ');
// config.headers.Authorization = newToken;
const contacts = await axios(req.config);
console.log(req.config);
const { data } = contacts;
res.status(200).render('contactList', {
title: 'All contacts',
data
});
});
答案 0 :(得分:0)
您可以在路由处理程序之前调用的中间件中访问ID。