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

React应用无法获取Node服务器发送的HTTP Cookies求助

问题描述

我尝试通过HTTP Cookies将accessToken和refreshToken从Node服务器发送至React前端,登录后希望在React中获取这些Cookie并存入React Context,但前端无法在请求头或其他途径获取到Cookie。Postman测试能看到Cookie,请问有没有办法在代码中访问这些Cookie?

Node 服务器代码

const accessToken = jwt.sign(
    { username },
    process.env.SECRET_KEY_ACCESS_TOKEN,
    {
      expiresIn: process.env.ACCESS_TOKEN_EXPIRATION.toString(),
    }
);

const refreshToken = jwt.sign(
    { username },
    process.env.SECRET_KEY_REFRESH_TOKEN,
    {
      expiresIn: process.env.REFRESH_TOKEN_EXPIRATION.toString(),
    }
);

response.cookie("accessToken", accessToken, {
    httpOnly: true,
    secure: false, 
    sameSite: "strict", 
    maxAge: 1 * 60 * 1000,
});
response.cookie("refreshToken", refreshToken, {
    httpOnly: true,
    secure: false, 
    sameSite: "strict", 
    maxAge: 2 * 60 * 1000, 
});

// *Return the response data
return response.json({ message: "Login Successful", authenticated: true });

React 前端代码

const sendRequest = async (payload) => {
 let { username, password } = payload;
    const API_URL = process.env.REACT_APP_API_URL;
    try {
      const response = await axios.post(
        `${API_URL}/api/auth/login`,
        {
          username,
          password,
        },
        { withCredentials: true }
      );
      console.log(response.headers); 
    } catch (error) {
      if (error.response) {
        console.error("Server Error:", error.response.data);
        return { error: error.response.data };
      } else if (error.request) {
        console.error("Network Error:", error.request);
        return { error: "Network Error" };
      } else {
        console.error("Error:", error.message);
        return { error: "Error" };
      }
    }
}
解决方案

你设置的Cookie带有httpOnly: true属性,这意味着浏览器会禁止前端JavaScript代码直接访问这些Cookie,这是一种安全机制,用来防止XSS攻击窃取Token。所以你没法在React代码里直接读取这两个Cookie的值。

如果想要把Token存入React Context,有两种可行方案:

方案1:修改Cookie属性(不推荐)

把httpOnly设为false,这样前端就能通过document.cookie读取Cookie内容。但这种做法会让Token暴露在XSS攻击风险下,不建议用于生产环境。

方案2:服务器额外返回Token(推荐)

在登录接口的响应体中,除了返回message和authenticated,同时把accessToken和refreshToken也返回回去。前端拿到响应数据后,直接提取这两个Token存入Context,同时浏览器会自动保存服务器设置的httpOnlyCookie,后续请求会自动带上这些Cookie用于鉴权。

修改后的Node代码示例:

// ... 生成Token的代码不变

response.cookie("accessToken", accessToken, {
    httpOnly: true,
    secure: false, 
    sameSite: "strict", 
    maxAge: 1 * 60 * 1000,
});
response.cookie("refreshToken", refreshToken, {
    httpOnly: true,
    secure: false, 
    sameSite: "strict", 
    maxAge: 2 * 60 * 1000, 
});

// 返回响应时带上Token
return response.json({ 
    message: "Login Successful", 
    authenticated: true,
    accessToken,
    refreshToken
});

修改后的React代码:

const sendRequest = async (payload) => {
 let { username, password } = payload;
    const API_URL = process.env.REACT_APP_API_URL;
    try {
      const response = await axios.post(
        `${API_URL}/api/auth/login`,
        {
          username,
          password,
        },
        { withCredentials: true }
      );
      // 从响应体提取Token并存入Context
      const { accessToken, refreshToken } = response.data;
      // 这里调用Context的set方法,比如:
      // authContext.setTokens({ accessToken, refreshToken });
      console.log("获取到Token:", accessToken, refreshToken);
    } catch (error) {
      // ... 错误处理代码不变
    }
}

补充说明

  • 即使前端不直接读取httpOnlyCookie,只要请求时设置了withCredentials: true,浏览器会自动在后续的同源请求头中带上这些Cookie,服务器可以正常验证Token。
  • 生产环境建议把secure设为true,确保Cookie只通过HTTPS传输,提升安全性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:52:58