繁体   English   中英

为什么不记名令牌给出错误“无法读取未定义的属性'拆分'”?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM