使用Serverless Framework+API Gateway为Lambda配置CORS及解决Cookie问题
解决方案
1. 修正Serverless.yml的CORS配置
现有配置缺少Cookie相关的响应头,需添加Cookie和Set-Cookie到允许的headers列表,确保跨域请求能正常传递Cookie:
provider: name: aws runtime: nodejs14.x memorySize: 3008 stage: dev timeout: 15 region: ap-south-1 cors: origins: - 'http://localhost:3000' - 'https://frontend-fms-vercel.vercel.app' # 保留其他需要的源 headers: - Content-Type - Authorization - Cookie - Set-Cookie allowCredentials: true apiGateway: binaryMediaTypes: - '*/*' functions: app: handler: src/app.handler events: - http: ANY /{proxy+} - http: ANY /
2. 配置Next.js请求的凭证选项
浏览器默认不会在跨域请求中发送Cookie,必须显式开启凭证携带:
使用Fetch API:
fetch('https://your-api-endpoint.dev/login', { method: 'POST', credentials: 'include', // 关键:开启凭证携带 headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: 'your-username', password: 'your-password' }) })
使用Axios:
import axios from 'axios'; axios.post('https://your-api-endpoint.dev/login', { username: 'your-username', password: 'your-password' }, { withCredentials: true // 关键:开启凭证携带 })
3. 同步API代码中的CORS中间件配置
如果API使用Express等框架,需确保CORS中间件与Serverless配置一致,避免规则冲突:
const cors = require('cors'); const allowedOrigins = [ 'http://localhost:3000', 'https://frontend-fms-vercel.vercel.app' ]; app.use(cors({ origin: (origin, callback) => { // 允许无Origin的请求(如Postman) if (!origin || allowedOrigins.includes(origin)) { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } }, credentials: true, allowedHeaders: ['Content-Type', 'Authorization', 'Cookie'], exposedHeaders: ['Set-Cookie'] // 确保前端能读取Set-Cookie头 }));
4. 调整Cookie的SameSite属性
跨域场景下,Cookie的SameSite属性需设置为None,并开启Secure(仅HTTPS环境),否则浏览器会阻止Cookie发送:
// 生成JWT并设置Cookie的示例 res.cookie('token', jwtToken, { httpOnly: true, secure: process.env.NODE_ENV === 'production', // 生产环境必须开启 sameSite: process.env.NODE_ENV === 'production' ? 'None' : 'Lax', maxAge: 24 * 60 * 60 * 1000 // 1天有效期 });
注意事项
- 避免同时在Serverless.yml和代码中间件重复配置CORS,优先以代码中间件配置为准,确保规则统一。
- 部署后需在线上环境测试,本地Serverless Offline的CORS行为可能与AWS API Gateway存在差异。
- 生产环境下,API域名和前端域名需均使用HTTPS,
Secure属性要求HTTPS才能生效。
内容的提问来源于stack exchange,提问作者Santosh Marar
相关产品推荐
相关产品推荐

