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

Node+Express中JWT与Cookie认证:React前端无法获取RefreshToken

MERN栈JWT刷新Token前端无法获取Cookie问题

问题详情

用MERN栈开发全栈网站,采用JWT的AccessToken+RefreshToken实现身份认证。登录接口通过res.cookie将RefreshToken存入Cookie,前端通过GET请求/refresh接口获取该Token。

当前问题:

  • Postman中登录后调用refresh接口,能正常获取RefreshToken;
  • React前端登录后调用同一接口,无法获取Token,但浏览器开发者工具显示响应已正确设置Cookie;
  • 已在多浏览器测试并清除缓存,问题仍存在。

相关代码

登录认证接口

router.post('/login',async (req,res)=>{

    const {username,password} = req.body;

    const user = await User.findOne({username:username});

    if (!user) return res.status(404).json({error:'there is no user with this username !'});

    const match = await bcrypt.compare(password,user.password);
    if(!match) return res.status(403).json({error:'invalid username or password '});

    
    const accessToken = jwt.sign({username:user.username},process.env.ACCESS_TOKEN_SECRET,{expiresIn:'900s'});
    const refreshToken = jwt.sign({username:user.username},process.env.REFRESH_TOKEN_SECRET,{expiresIn:'1d'});

    user.refreshToken = refreshToken;
    await user.save();

    
    res.cookie('refresh',user.refreshToken,{httpOnly:true,maxAge:1000*3600*24,domain:'localhost',path:'/'});

    res.json({accessToken:accessToken,username:user.username,id:user._id});
});

Token刷新接口

router.get('/',async(req,res)=>{

    const cookies = req.cookies;
    if(!cookies?.refresh) return res.json('no cookies');

    res.json({refreshToken:cookies.refresh});
});

解决办法

问题核心是跨域请求时前端未携带Cookie:Postman默认自动携带同域Cookie,但React使用的fetch或axios请求默认不会发送Cookie,需同时配置前后端开启凭证支持。

1. 后端配置CORS允许凭证

确保Express后端的CORS配置开启credentials: true,且指定具体前端origin(不能用*,否则凭证会失效):

const cors = require('cors');
app.use(cors({
  origin: 'http://localhost:3000', // 替换为你的React前端运行地址
  credentials: true
}));

2. 前端请求配置携带Cookie

  • 使用fetch时,添加credentials: 'include'参数:
fetch('http://localhost:5000/refresh', { // 替换为你的后端接口地址
  credentials: 'include'
})
.then(res => res.json())
.then(data => console.log(data));
  • 使用axios时,设置withCredentials: true:
axios.get('http://localhost:5000/refresh', {
  withCredentials: true
})
.then(res => console.log(res.data));

3. Cookie配置检查

确认res.cookie参数无问题:

  • domain: 'localhost'符合前后端同域名场景;
  • httpOnly仅禁止前端JS读取Cookie,不影响请求自动携带;
  • path: '/'确保Cookie可被所有路径的接口读取,配置正确。

内容的提问来源于stack exchange,提问作者Razine Al

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 11:42:05