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

React使用Axios调用/api/user/is-auth接口时出现401未授权错误求助

问题描述

我正在使用React和Axios开发Web应用,尝试调用/api/user/is-auth接口检查用户是否已认证,但遇到如下错误:

GET http://localhost:4000/api/user/is-auth 401 (Unauthorized)

控制台中显示:

Auth check failed: Request failed with status code 401

我已确认后端API需要授权token,以下是发起请求的相关代码:

const fetchUser = async () => {
  try {
    const { data } = await axios.get('/api/user/is-auth', {
      withCredentials: true
    });

    if (data.success) {
      setUser(data.user);
    }
  } catch (error) {
    console.log('Auth check failed:', error.message);
    setUser(null);
  }
};

我采用基于JWT的认证方式,以下是后端中间件及接口的相关代码:

const authUser = async (req, res, next) => {
  const { token } = req.cookies;

  if (!token) {
      return res.status(401).json({ success: false, message: 'Unauthorized' });
  }

  try {
      const tokenDecode = JWT.verify(token, process.env.JWT_SECRET);

      if (tokenDecode.id) {
          req.userId = tokenDecode.id;
          next();
      } else {
          return res.status(401).json({ success: false, message: 'Unauthorized' });
      }
  } catch (error) {
      res.status(401).json({ success: false, message: error.message });
  }
};

请求Cookie截图

请问为何会出现401错误?请求设置中可能遗漏了什么?

可能的原因及解决方案

从代码和截图来看,401错误的核心是后端没拿到有效的JWT token,或者token验证失败,以下是几个排查方向:

  • Cookie跨域配置问题
    前端开启了withCredentials: true,但后端必须配合正确的CORS配置:

    • 后端需设置响应头Access-Control-Allow-Credentials: true
    • Access-Control-Allow-Origin不能设为*,必须指定前端的具体域名(比如http://localhost:3000)
  • Cookie属性设置问题
    检查后端设置Cookie时的关键属性:

    • SameSite:前后端域名不同时,需设为Lax或None(设为None必须搭配Secure属性,仅HTTPS环境生效)
    • domain:如果前端是localhost:3000、后端是localhost:4000,需将Cookie的domain设为.localhost,确保跨端口能共享
    • path:需设为'/',保证所有接口都能访问到该Cookie
  • Token有效性问题
    截图里能看到Cookie存在token,但要确认:

    • 该token是后端签发的有效JWT吗?可以用JWT解码工具验证内容和签名
    • token是否过期?检查JWT的exp字段
    • 后端的JWT_SECRET和签发token时的密钥是否一致?密钥不匹配会直接导致验证失败
  • Axios基础配置问题
    确认Axios的baseURL是否正确设置,确保请求的目标地址和后端一致,避免路径错误导致Cookie无法正常携带

内容的提问来源于stack exchange,提问作者Muhammad Fattan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 04:12:38