【问题标题】:jsonwebtoken not in headersjsonwebtoken 不在标头中
【发布时间】:2020-04-24 09:07:53
【问题描述】:

我在 express 应用程序中遇到了 jsonwebtoken 的问题,我无法验证中间件上的 jwt,因为 req.headers 中不存在 jwt 这是我的代码:

const payload = { email, role: "User" };

jwt.sign(
        payload,
        process.env.SECRET_USER,
        {
           expiresIn: 60
        },
        (err, token) => {
        if (err) return err;
           res.send(token);
        }
    );

当我使用邮递员时,我没有错误并且令牌已成功发送。 但是在我的中间件中(用于检查用户是否已登录),我尝试使用 console.log(req.headers) 并且没有键“Authorization: Bearer [TOKEN]”

中间件:

const jwt = require("jsonwebtoken");
require("dotenv").config();

exports.isUserAuth = (req, res, next) => {
  console.log(req.headers);
  const token = req.headers.authorization.split(" ")[1];
};

【问题讨论】:

  • 请给我们你想要获取Auth-Header的中间件的代码。
  • 您的客户端如何调用 API 并附加令牌?

标签: node.js express jwt


【解决方案1】:

您是否在从客户端向服务器发出请求之前设置了令牌? 例如假设您在用户登录后使用axios 发出http 请求:

axios.get('/check', {
     headers: {
        'Authorization': 'Bearer ' + 'bear-token-received-after-user-logged-in'
    }})

每次向服务器发出请求时都需要提供令牌。

【讨论】:

    猜你喜欢
    • 2018-12-11
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2015-05-06
    • 2023-02-06
    • 2017-10-13
    相关资源
    最近更新 更多