【问题标题】:Header authorization doesn't exist标头授权不存在
【发布时间】:2020-11-13 07:51:19
【问题描述】:

我正在尝试在我的 API 上发送一个 jwt 令牌,但它不起作用,而我做的事情与互联网课程相同。 似乎授权标头未定义,并且不接受我在 json 响应中提供的令牌。

这是我的登录功能截图:

login(req:Request, res:Response) {
    const id = this._id;
    bcrypt.compare(req.query.password, this._password)
        .then(function (valid: any) {
            if (!valid) {
                return res.status(401).json({error: 'Mot de passe incorrect !'});
            }
            res.status(200).json({
                hostId: id,
                token: jwt.sign({hostId : id}, 'RANDOM_TOKEN_SECRET', {expiresIn: '12h'})
                });
            })
            .catch(function (error:any) {
                res.status(500).json({error})
            })
        .catch(function (error:any)  {
            res.status(500).json({error});
        });
}

这是我的认证功能:

static auth(req: Request, res: Response, next: any) {
    try {
        console.log('bonjour');
        console.log(req.headers.authorization);
        console.log(req.body.hostId);
        let token = req.headers.authorization?.split(' ')[1];
        const decodedToken = jwt.verify(token, 'RANDOM_TOKEN_SECRET');
        const id = decodedToken.hostId;
        if (req.body.hostId && req.body.hostId !== id) {
            throw 'Invalid user ID';
        } else {
            next();
        }
    } catch (error) {
        res.status(401).json({error: error.message});
    }
}

我已经在我的服务器类中设置了我的标题:

export default class Server {
constructor() {
    app.use(function (req:Request, res:Response, next:any) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization, Content-Type, Accept");
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
        next();
    })
    .get('/', function (req:Request, res:Response) {
        res.send("Serveur démarré");
    })
    .listen(8080);
}

}

我将 nodejs 与 express、mongoose 一起用于我的数据库和打字稿。

我希望你能帮助我:)

【问题讨论】:

    标签: json express authorization token request-headers


    【解决方案1】:

    您应该在前端而不是服务器端将标头设置为 { Authorization: Bearer ${token} }

    【讨论】:

    • 但是考虑到它是一个 API 所以没有前端
    • 整个过程如下: 1、Client向服务器发送'/login'请求,http-body中带有名称和密码。 2、服务器检查body参数。如果参数正确,“/login” api 中的服务器响应带有 auth-token。 3. 客户端收到令牌并缓存它。客户端发送的以下 http 请求应在标头中包含令牌。 4.服务器检查每个http请求的(不包括登录api本身)标头,以确保客户端是否是授权用户。
    • 好的,谢谢,我明白了,所以在我只处理服务器端请求和响应的情况下,我必须在像邮递员这样的软件中手动将令牌放入授权标头中,对吗?
    猜你喜欢
    • 2019-07-23
    • 2020-04-28
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2020-06-03
    • 2019-06-18
    • 1970-01-01
    相关资源
    最近更新 更多