英文:
NodeJS/Express - Cannot Read All Req.Headers
问题
使用ReactJs前端和NodeJs/Express后端构建一个简单的ToDo应用程序。我配置了前端以将userId包含为请求头:
export default function authHeader() {
const user = JSON.parse(localStorage.getItem('user'));
if (user && user.accessToken) {
// return { Authorization: 'Bearer ' + user.accessToken }; // 用于Spring Boot后端
return {
'x-access-token': user.accessToken,
'userid': user.id
}; // 用于Node.js Express后端
} else {
return {};
}
}
这个头部随着Axios请求一起被包含:
// 列出所有群组成员
listMembers() {
return http.get(`/group`, { headers: authHeader() });
}
因此,我可以在请求中看到这些头部:
我的身份验证中间件的一部分引用了访问令牌:
verifyToken = (req, res, next) => {
let token = req.headers["x-access-token"];
if (!token) {
return res.status(403).send({
message: "未提供令牌!"
});
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.status(401).send({
message: "未经授权!"
});
}
req.userId = decoded.id;
next();
});
};
顶部的req.headers
行可以轻松地从头部"“x-access-token”中提取令牌。然而,出于调试目的,我尝试提取头部userId值,使用let token = req.headers["userid"];
,但在我的调试工具中它只是返回未定义。为什么它能够提取"x-access-token"头部,但不能提取userId?我的最终目标是在后端SQL查询中引用req.header userId值,这只是一个测试。
英文:
Building a simple ToDo app with ReactJs frontend and NodeJs/Express backend. I configured my frontend to include userId as a request header:
export default function authHeader() {
const user = JSON.parse(localStorage.getItem('user'));
if (user && user.accessToken) {
// return { Authorization: 'Bearer ' + user.accessToken }; // for Spring Boot back-end
return {
'x-access-token': user.accessToken,
'userid': user.id
}; // for Node.js Express back-end
} else {
return {};
}
}
This header is included with the Axios request:
// List all Group Members
listMembers() {
return http.get(`/group`, { headers: authHeader() });
}
Consequently, I can see the headers in the request:
Part of my auth middleware references the access token:
verifyToken = (req, res, next) => {
let token = req.headers["x-access-token"];
if (!token) {
return res.status(403).send({
message: "No token provided!"
});
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.status(401).send({
message: "Unauthorized!"
});
}
req.userId = decoded.id;
next();
});
};
The req.headers lines near the top is able to pull the token from header "x-access-token" with no problem. HOWEVER - for debug purposes, I have tried to pull the header userId value instead using let token = req.headers["userid"]; but this simply comes back as undefined in my debug tools. Why can it pull x-access token header but not userId? My eventual goal is to refer to the req.header userId value in backend SQL queries, this is just a test.
答案1
得分: 0
在管道中有一个大写错误。 @Sardar的评论是正确的,请确保一切拼写正确并且大小写匹配。
英文:
It ended being a capitalization error somewhere in pipeline. @Sardar's comment was on the money, make sure everything is spelled correctly and matches case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论