[英]Why I receive error: TypeError: Cannot read property of 'split' of undefined
[英]why does bearer token gives error “Cannot read property 'split' of undefined”?
我在這里要做的就是保護快速路由..這里發送請求從反應到快速路由器:
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));
現在這個請求到達 express 路由器:
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 property 'split' of undefined
它適用於 postman 但是當我從 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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.