You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express+React项目前端Fetch请求JWT授权失败求助

问题:JWT授权在PUT /image接口失效,authHeader为undefined

项目中使用JWT实现前后端全局授权,其余接口均正常,但/image的PUT接口仅从前端调用时始终授权失败,后端控制台显示authHeader为undefined。

前端代码

fetch('http://localhost:3000/image', {
            method: 'PUT',
            credentials: 'include',
            headers: {
              Authentication: `Bearer ${this.state.Bearer}`,
              Accept: 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              id: this.state.user.id
            })
          })
            .then(response => response.json())
            .then(count =>
              this.setState(Object.assign(this.state.user, { entries: count }))
            )

JWT中间件代码

//authenticate access token
function authenticateToken(req, res, next) {
  console.log(req.path)
  if (['/signin', '/register','/signout'].includes(req.path)) {
    return next();
  }
      const authHeader = req.headers['authorization'];
      console.log(authHeader, "authHeader");
      const token = authHeader && authHeader.split(' ')[1]
      if (token == null) return res.sendStatus(401)
      jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
        if (err) return res.sendStatus(403)
        console.log(err)
        req.user = user;
        next()
      })
    }

问题原因

核心问题是请求头字段名称不匹配:

  • 前端请求中设置的头字段为Authentication
  • 后端中间件尝试获取的是req.headers['authorization']

HTTP协议头字段本身大小写不敏感,但Node.js会自动将所有请求头字段名转换为小写存储在req.headers中。因此前端的Authentication会被转为authentication,后端取authorization自然无法获取到值。另外,标准的HTTP授权头字段名称是Authorization,建议遵循规范。

解决方案

任选以下一种方式修复:

方式1:修改前端代码(推荐,符合标准)

将请求头字段改为标准的Authorization:

fetch('http://localhost:3000/image', {
  method: 'PUT',
  credentials: 'include',
  headers: {
    Authorization: `Bearer ${this.state.Bearer}`, // 修改此处字段名
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    id: this.state.user.id
  })
})
// 后续代码保持不变

方式2:修改后端中间件(不推荐,不符合规范)

调整后端获取头字段的名称为小写的authentication:

const authHeader = req.headers['authentication']; // 修改此处字段名

验证

修改完成后重新测试PUT /image接口,后端控制台应能正常打印authHeader的值,授权流程将正常执行。

内容的提问来源于stack exchange,提问作者Almog Hasson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:05:18