我是nodejs和Typescript的新手,我想在req.body
中添加一个新参数,例如req.body.jwt_token
。
我正在使用中间件更新请求数据模型。 问题是我能够访问(console.log运行)新密钥req.body.jwt_token
仅在该功能中起作用,除此之外不能访问(甚至不存在)。
我想在某些控制器中使用req.body.jwt_token
。
export function httpsProtocol(req: Request, res: Response, next: NextFunction) {
try {
if (req.headers.authorization != undefined) {
let authorization = req.headers.authorization;
let authorizationArr: string[] = authorization.split('Bearer')
if (authorizationArr[1] != undefined) {
let jwtToken = "Bearer " + authorizationArr[1].trim();
req.headers.Authorization = jwtToken;
req.body.jwt_token = authorizationArr[1].trim();
console.log(req.body.jwt_token); //able to console this
}
}
} catch (error) {
return res.status(422).json({
message: "something goes wrong",
error: error
});
}
next();
};
请提出解决方案的建议此问题。我如何在nodejs和typescript中实现这一点。我正在使用express作为框架
谢谢
💡您无法在控制器中访问
req.body.jwt_token
的唯一原因是在设置该值之前,您需要next()
。
👨🏽🏫确保在next()
条件内添加if/else
。因此,您可以复制 below下面的代码并使用它:
export function httpsProtocol(req: Request, res: Response, next: NextFunction) {
try {
if (req.headers.authorization != undefined) {
let authorization = req.headers.authorization;
let authorizationArr: string[] = authorization.split('Bearer')
if (authorizationArr[1] != undefined) {
let jwtToken = "Bearer " + authorizationArr[1].trim();
req.headers.Authorization = jwtToken;
req.body.jwt_token = authorizationArr[1].trim();
console.log(req.body.jwt_token); //able to console this
// your next here
next();
} else {
next(); // next or do some stuff
}
} else {
next(); // next or do some stuff
}
} catch (error) {
return res.status(422).json({
message: "something goes wrong",
error: error
});
}
// next(); your next here only make your req.body.jwt_token is undefined
};
也许此答案将帮助您了解原因:passing value from middleware to controller in restify using req.data is not working?
希望它能对您有所帮助。