简体   繁体   English

JWT-Node 身份验证 - req.headers[''authorization"] 未定义

[英]JWT-Node authentication - req.headers[''authorization"] is Undefined

I try to set Token then get token from header but it always shows "undefined" when i console.log(req.headers['authorization'])我尝试设置令牌然后从 header 获取令牌,但是当我 console.log(req.headers['authorization']) 时它总是显示“未定义”

Here is some code这是一些代码

const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const accessTokenSecret = 'youraccesstokensecret';
app.listen(8080, () => {
    console.log('Authentication service started on port 8080');
});

I set token我设置令牌

app.get("/createJWT",function(req,res){
    const accessToken = jwt.sign({ username: "myName"}, accessTokenSecret);

    res.json({
        accessToken
    });
})

the middleware (I show req.headers['authorization'] is undefined)中间件(我显示 req.headers['authorization'] 未定义)

const authenticateJWT = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    console.log(authHeader)
    if (authHeader) {
        const token = authHeader.split(' ')[1];

        jwt.verify(token, accessTokenSecret, (err, user) => {
            if (err) {
                return res.sendStatus(403);
            }

            req.user = user;
            next();
        });
    } else {
        res.sendStatus(401);
    }
};

And finally, I access a route to test, req.headers['authorization'] does not have values.最后,我访问了一条测试路线, req.headers['authorization'] 没有值。

app.get("/check",authenticateJWT,function(req, res){
    res.send("ok")
})

please help me, thanks请帮助我,谢谢

So when you are calling the API form the frontend or say you are checking the API with postman are you setting up the header while requesting /check ? So when you are calling the API form the frontend or say you are checking the API with postman are you setting up the header while requesting /check ? (I am not talking about your /createJWT which creates the token and sends it as a response) (我不是在谈论您的/createJWT创建令牌并将其作为响应发送)

In your frontend code/postman you need to explicitly add the header authorization JWTtoken while creating an HTTP request and after that your backend will receive it.在您的前端代码/邮递员中,您需要在创建 HTTP 请求时显式添加 header authorization JWTtoken ,然后您的后端将收到它。 Kindly check if this is not being done.请检查这是否没有完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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