【问题标题】:Express middleware not picking up header despite it being sent in request尽管是在请求中发送的,但 Express 中间件没有拾取标头
【发布时间】:2020-09-07 14:15:09
【问题描述】:

我的后端服务器上运行了一个快速 REST API。对于身份验证,我使用 JWT 并拥有快速中间件,该中间件可以获取访问令牌并使用密钥对其进行验证。目前,尽管发送了请求,但中间件并未获取请求中的 auth_token 标头。任何帮助表示赞赏,代码如下。

const jwt = require('jsonwebtoken')

function auth(req, res, next) {
    const token = req.header('auth_token');

    if (!token) {
        res.status(401).json({ msg: "No token, authorization denied" })
    } else {
        try {
            const decoded = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET)
            req.user = decoded

            next()
        } catch (err) {
            res.status(400).json({ msg: "Token invalid" })
        }
    }
}

module.exports = auth;

请求

:authority: api.parotta.xyz
:method: GET
:path: /api/users/userInfo
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
auth_token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZjUxYmIwODQ2YzQyYTAwMDZmNGFiOGIiLCJpYXQiOjE1OTk0NTc5MTgsImV4cCI6MTU5OTQ1ODgxOH0.QTjfANYGQUYAhfqQzk_B0PId7pr0jMpu7fS1rIOYIcI
origin: https://www.parotta.xyz
referer: https://www.parotta.xyz/dashboard
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1

cors

app.use(
    cors({
        credentials: true,
        origin: process.env.ORIGIN
    })
);

ORIGIN=https://www.parotta.xyz

【问题讨论】:

  • 能否在将标头设置为响应时包含一个 sn-p?
  • 错误 [ERR_HTTP_HEADERS_SENT]:无法在将标头发送到客户端后设置标头,这是我仅在生产中收到的错误
  • 请显示发送标头的客户端代码。错误可能就在这一端。
  • ``` const response = await axios.get('api.parotta.xyz/api/users/userInfo', { headers: { auth_token: getAccessToken() } }) ``
  • 我觉得应该是req.headers而不是req.header

标签: node.js express jwt


【解决方案1】:

试试这个

我已经创建了一个中间件,我已经用邮递员测试了这个,希望对你有帮助,根据你的需要编辑它

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '');
        const decode = jwt.verify(token, 'xyz');
        const user = await User.findOne({
            _id: decode._id,
            'tokens.token': token //mongoose syntax
        })

        if (!user) {
            throw new Error()
        }

        req.token = token;
        req.user = user;
        next();

    } catch (error) {
        res.status(401).send({
            error: 'Please Authenticate'
        })
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2019-02-17
    • 2014-06-13
    • 2013-08-13
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    相关资源
    最近更新 更多