AWS Serverless部署Nest.js后端出现CORS跨域错误求助
解决AWS Serverless部署后Nest.js的CORS问题
1. 修正Nest.js的CORS配置(核心问题)
你当前的Nest.js代码硬编码了origin: 'http://localhost:3000',部署后前端是线上域名,这个配置完全不匹配,直接导致CORS头无法正确返回。必须改成支持线上域名的动态配置:
方案一:用环境变量指定允许的Origin
修改serverless.ts中的CORS配置:
app.use( cors({ origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http://localhost:3000', credentials: true, }), );
在.env文件中添加线上前端域名(多个用逗号分隔):
ALLOWED_ORIGINS=https://your-nextjs-production-domain.com,http://localhost:3000
同时在serverless.yaml的environment区块加入这个变量:
environment: # ...其他已有变量 ALLOWED_ORIGINS: ${env:ALLOWED_ORIGINS}
方案二:动态验证Origin(更灵活)
如果需要支持多个域名且不想每次改环境变量,用函数动态判断:
const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:3000']; 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, }), );
2. 统一Serverless的API配置,避免冲突
你的serverless.yaml同时混用了httpApi(API Gateway v2)和http事件(API Gateway v1),两者的CORS逻辑完全不同,极易导致配置冲突。二选一即可:
选项A:使用API Gateway v2(httpApi)
保留provider下的httpApi配置,把functions里的http事件改成httpApi:
provider: # ...其他配置 httpApi: cors: allowedOrigins: ${env:ALLOWED_ORIGINS} allowedMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'] allowedHeaders: ['Content-Type', 'Authorization'] allowCredentials: true functions: main: handler: dist/serverless.handler timeout: 30 role: <value> events: - httpApi: path: / method: ANY - httpApi: path: "{proxy+}" method: ANY
选项B:使用API Gateway v1(http事件)
删除provider下的httpApi区块,给每个http事件单独配置CORS:
provider: # ...其他配置,移除httpApi部分 functions: main: handler: dist/serverless.handler timeout: 30 role: <value> events: - http: path: / method: ANY cors: origin: ${env:ALLOWED_ORIGINS} headers: Content-Type,Authorization allowCredentials: true - http: path: "{proxy+}" method: ANY cors: origin: ${env:ALLOWED_ORIGINS} headers: Content-Type,Authorization allowCredentials: true
3. 验证AWS控制台的CORS配置(避免手动修改冲突)
如果用API Gateway v1,进入AWS控制台的API Gateway服务,找到你的API,检查资源下的CORS配置:
- 确认
Access-Control-Allow-Origin和你配置的线上域名一致 - 必须勾选
Access-Control-Allow-Credentials - 允许的Headers、Methods要和serverless配置匹配
⚠️ 注意:Serverless框架部署会覆盖控制台的手动配置,所以优先保证yaml配置正确,部署后不要手动改控制台CORS。
4. 部署后验证
部署完成后,用curl测试CORS头是否正确返回:
curl -I -H "Origin: https://your-nextjs-domain.com" https://your-api-domain.com/your-test-endpoint
检查响应头是否包含:
Access-Control-Allow-Origin: https://your-nextjs-domain.comAccess-Control-Allow-Credentials: true
如果还是报错,去CloudWatch日志里看Nest.js的请求处理日志,排查是否有其他中间件拦截了请求,或者CORS配置未生效。
内容的提问来源于stack exchange,提问作者palalele
相关产品推荐
相关产品推荐

