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

MERN应用登录正常但访问关于页提示未找到授权令牌错误怎么解决?

问题根因

错误No authorization token was found是express-jwt中间件未从请求中成功获取到有效JWT令牌导致,结合给出的代码,有4处需要修正:


修正步骤

  1. 前端请求补充Authorization头
    当前的/about接口请求没有携带登录后生成的令牌,默认express-jwt会从请求头的Authorization字段提取令牌,需要在前端请求中添加对应配置:
// AboutUs.js 修正后的callAboutPage方法
const callAboutPage = async()=>{
  try{
    // 替换key为你登录成功后存储token的实际字段名
    const token = localStorage.getItem('loginToken')
    const res = await fetch('/about',{
      method:"GET",
      headers:{
        Accept:'application/json',
        'Content-Type':'application/json',
        // 新增Authorization头,固定格式为 Bearer + 空格 + 令牌
        'Authorization': `Bearer ${token}`
      },
      credentials:"include"
    })

    const data = await res.json();
    console.log(data)
  }
  catch(err){
    console.log(err);
    history.push('/login')
  }
}

如果你的令牌是存在Cookie中,需要补充express-jwt的自定义令牌提取逻辑:

// auth.js/controller 修正后的isSignedIn中间件
exports.isSignedIn = expressJwt({
  secret: process.env.SECRET,
  algorithms: ['RS256'],
  userProperty: "Auth",
  // 新增自定义令牌提取逻辑,优先从请求头取,取不到再从Cookie取
  getToken: (req) => {
    if (req.headers.authorization?.split(' ')[0] === 'Bearer') {
      return req.headers.authorization.split(' ')[1];
    } 
    return req.cookies?.token || null
  }
});
  1. 补充req.profile挂载中间件
    你的isAuthenticated中间件需要读取req.profile字段校验身份,但当前路由没有对应逻辑挂载该字段,需要新增userById中间件:
// 先在user相关controller中新增userById方法,替换为你实际的User模型引入
const User = require('../models/user')
exports.userById = (req, res, next, id) => {
  User.findById(id).exec((err, user) => {
    if (err || !user) return res.status(400).json({error: "用户不存在"})
    req.profile = user
    next()
  })
}

// 路由文件中注册参数处理逻辑,调整路由配置
const { userById } = require('../controllers/user')
router.param("userId", userById)
// 路由补充userId参数,userById会自动提取参数值查询用户挂载到req.profile
router.get('/about/:userId',isSignedIn,userById,isAuthenticated,(req,res)=>{
  res.send("A protected Route")
});
  1. 校验JWT签名算法一致性
    你当前express-jwt配置的算法是RS256非对称加密,需要确认登录接口生成令牌时的jwt.sign配置是否和该算法一致:
  • 如果生成令牌用的是HS256对称加密,把algorithms: ['RS256']改为algorithms: ['HS256']即可
  • 如果确实用的是RS256,需要确认process.env.SECRET配置的是RSA公钥,生成令牌时用的是对应RSA私钥签名

内容的提问来源于stack exchange,提问作者Monu Patil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 23:30:01