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

React请求/jwtid接口时Token未定义,Postman可正常获取

问题分析与解决方案

React应用调用/jwtid路由时,服务器端通过req.cookies.jwt获取Token始终为undefined,但Postman测试该路由可正常返回结果。结合代码细节,问题出在请求参数传递错误、路由取值逻辑错误以及前后端Token传递方式不匹配上,以下是具体修正方案:


关键修正点

1. 修复路由处理函数的取值错误

原路由代码中,verifyToken中间件将解码后的用户ID存入req.id,但路由处理错误地使用res.locals.id取值,导致即使Token验证通过,返回结果也会是undefined。

修正/jwtid路由代码:

app.get('/jwtid', verifyToken, (req, res) => {
  // 替换res.locals.id为req.id,与中间件逻辑对齐
  res.status(200).send(req.id)
});

2. 修正前端Axios请求的配置错误

原请求存在语法错误(多余的config参数、GET请求携带body),且未按照服务器期望的方式传递Token,分两种适配方案:

方案A:保持服务器从Cookie读取Token(原逻辑)

如果登录时服务器已通过res.cookie('jwt', token)设置Cookie,前端只需确保请求携带Cookie:

  • 修正App.js中的Axios请求:
axios({
  method: "get",
  url: `${process.env.REACT_APP_API_URL}jwtid`,
  withCredentials: true // 允许跨域请求携带Cookie
})
.then(function (response) {
  console.log(response.data);
  return response.data;
})
.then((res) => {
  if (res.error) { 
    console.log(res.error);
    alert("The response data is invalid")
  }
})
.catch((err) => console.log("No token"))
  • 服务器端必须配置CORS允许携带凭证:
const cors = require('cors');
app.use(cors({
  origin: 'http://localhost:3000', // 替换为你的React应用地址
  credentials: true
}));

方案B:适配localStorage存储Token,服务器从Header读取

如果前端将Token存在localStorage,修改服务器中间件支持从Authorization Header获取Token:

  • 修正authJwt.js的verifyToken函数:
verifyToken = (req, res, next) => {
  // 优先从Cookie取,其次从Authorization Header取
  let token = req.cookies.jwt;
  if (!token) {
    const authHeader = req.headers.authorization;
    if (authHeader && authHeader.startsWith('Bearer ')) {
      token = authHeader.slice(7);
    }
  }

  console.log(token);
  if (!token) {
    return res.status(403).send({
      message: "No token provided!"
    });
  }

  jwt.verify(token, config.secret, (err, decoded) => {
    if (err) {
      return res.status(401).send({  
        message: "Unauthorized!"
      });
    }
    req.id = decoded.id;
    next();
  });
};
  • 前端Axios请求设置Header:
axios({
  method: "get",
  url: `${process.env.REACT_APP_API_URL}jwtid`,
  headers: {
    'Authorization': `Bearer ${user}` // user为localStorage取出的Token字符串
  }
})
// 后续then/catch逻辑不变

3. 验证前端Token格式

确保localStorage.getItem("user")取出的是纯JWT字符串,而非包含Token的对象。可通过控制台打印user确认格式是否正确。


内容的提问来源于stack exchange,提问作者Elodie Jean

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:48:18