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

React应用无法接收AWS Lambda后端Cookie问题求助

React无法接收Serverless/Lambda返回的Cookie(本地serverless-offline测试)

问题背景

使用Serverless Framework开发基于AWS Lambda的服务,通过serverless-offline本地测试时,后端Lambda返回Set-Cookie响应头,Postman可正常接收Cookie,但React应用通过fetch请求后,控制台输出的响应头为空,无法获取Cookie。

现有代码

Lambda后端代码

import { APIGatewayProxyHandlerV2 } from "aws-lambda";

const oneDayMillis = 1 * 24 * 60 * 60 * 1000;

export const handler: APIGatewayProxyHandlerV2 = async (event) => {
  const expires = new Date(Date.now() + oneDayMillis).toUTCString();
  return { 
    headers: {'Set-Cookie': `name=hardyeats; Path=/; Expires=${expires}; ; httponly;`},
    statusCode: 200 
  }
}

serverless.ts跨域配置

httpApi: {
  cors: {
    allowedOrigins: ["${self:custom.env.${opt:stage}.ALLOWED_ORIGIN}"],
    allowedHeaders: ['Content-Type'],
    allowedMethods: ['GET','POST','PUT','DELETE'],
    allowCredentials: true
  }
},

React前端代码

function Login() {
  useEffect(()=>{
    fetch(`${process.env.REACT_APP_API_SERVER_URL}/oauth/login`)
    .then(res => console.log(res.headers))
  },[])

  return (
    <></>
  );
}

解决方案

1. 给fetch请求添加credentials配置

跨域请求要接收Cookie,必须在fetch中明确设置credentials: 'include',否则浏览器会忽略响应中的Set-Cookie头:

useEffect(()=>{
  fetch(`${process.env.REACT_APP_API_SERVER_URL}/oauth/login`, {
    credentials: 'include' // 关键配置
  })
  .then(res => {
    console.log('响应状态:', res.status);
    // 注意:HttpOnly类型的Cookie无法通过res.headers读取,需通过浏览器开发者工具查看
  })
},[])

2. 修正Set-Cookie的格式

后端返回的Set-Cookie存在多余分号,会导致解析异常,调整格式并规范参数大小写:

return { 
  headers: {'Set-Cookie': `name=hardyeats; Path=/; Expires=${expires}; HttpOnly;`},
  statusCode: 200 
}

3. 确保CORS配置的正确性

  • allowedOrigins不能使用通配符*,必须指定具体的前端域名(比如本地测试的http://localhost:3000),因为allowCredentials: true时,浏览器不允许通配符来源。
  • 若serverless-offline版本过低可能存在HttpApi的CORS兼容问题,可尝试升级serverless-offline包。

4. 理解HttpOnly Cookie的限制

你的Cookie设置了HttpOnly标记,这意味着该Cookie只能由浏览器管理,无法通过JavaScript代码读取,所以通过res.headers.get('Set-Cookie')或document.cookie都无法看到这个Cookie。需要打开浏览器开发者工具,在Application标签页的Cookies栏目下查看是否已成功存储该Cookie。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:55:26