为什么不记名令牌会出现错误 "Cannot read property 'split' of undefined"?
why does bearer token gives error "Cannot read property 'split' of undefined"?
我在这里所做的只是保护快速通道..
这里从 React 向 Express 路由器发送请求:
Axios.post("http://localhost:5000/users/userinfo/" + this.state.id, {
headers: { Authorization: "Bearer " + "jsonwebtoken" },
data:{this.state.data},
})
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
现在这个请求到达了快速路由器:
router.post("/userinfo/:id", verifyToken, (req, res) => {
res.json({ msg: "authorized", data: req.payback });
)}
这里是 verfifyToken 中间件:
module.exports = function (req, res, next) {
try {
const decode = req.headers.authorization.split(" ")[1];
req.token = decode;
jwt.verify(req.token, process.env.JWT_SECRET, (err, data) => {
if (!err) {
req.payback = data;
next();
} else {
return res.json({ error: "Unauthorized User!" });
}
});
} catch (error) {
console.log(error);
res.json({ error: error });
}
};
但这给了我错误:TypeError: Cannot read 属性 'split' of undefined
它与邮递员一起工作正常,但是当我从 React 发送请求时,它不断重复这个错误,我被困在这里,请帮忙!
axios.post
具有以下签名 axios#post(url[, data[, config]])
所以你必须改为执行以下操作。
Axios.post("http://localhost:5000/users/userinfo/" + this.state.id,
this.state.data, {
headers: { Authorization: "Bearer " + "jsonwebtoken" },
})
此外,如果您只需要一个 header 字段,最好使用 req.get()
或别名 req.header
以避免大小写不匹配
req.header('Authorization')
我在这里所做的只是保护快速通道.. 这里从 React 向 Express 路由器发送请求:
Axios.post("http://localhost:5000/users/userinfo/" + this.state.id, {
headers: { Authorization: "Bearer " + "jsonwebtoken" },
data:{this.state.data},
})
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
现在这个请求到达了快速路由器:
router.post("/userinfo/:id", verifyToken, (req, res) => {
res.json({ msg: "authorized", data: req.payback });
)}
这里是 verfifyToken 中间件:
module.exports = function (req, res, next) {
try {
const decode = req.headers.authorization.split(" ")[1];
req.token = decode;
jwt.verify(req.token, process.env.JWT_SECRET, (err, data) => {
if (!err) {
req.payback = data;
next();
} else {
return res.json({ error: "Unauthorized User!" });
}
});
} catch (error) {
console.log(error);
res.json({ error: error });
}
};
但这给了我错误:TypeError: Cannot read 属性 'split' of undefined
它与邮递员一起工作正常,但是当我从 React 发送请求时,它不断重复这个错误,我被困在这里,请帮忙!
axios.post
具有以下签名 axios#post(url[, data[, config]])
所以你必须改为执行以下操作。
Axios.post("http://localhost:5000/users/userinfo/" + this.state.id,
this.state.data, {
headers: { Authorization: "Bearer " + "jsonwebtoken" },
})
此外,如果您只需要一个 header 字段,最好使用 req.get()
或别名 req.header
以避免大小写不匹配
req.header('Authorization')