无法在AWS Serverless Lambda中设置Access-Control-Allow-Credentials响应头
解决方案
方案一:简化配置,依赖Serverless自动生成CORS响应头
你的配置中同时设置了cors.allowCredentials: true和response.headers中的Access-Control-Allow-Credentials,可能导致规则冲突。尝试移除手动添加的response配置,让Serverless框架根据cors配置自动生成OPTIONS请求的响应头:
- http: path: /path method: post authorizer: ${self:custom.authorizer} cors: origins: - http://localhost:8080 - http://localhost:8081 headers: ${self:custom.allowedHeaders} allowCredentials: true
之后执行serverless deploy全量部署(不要使用deploy function,因为CORS配置属于API Gateway全局资源设置,需要全量部署生效),再测试OPTIONS请求的响应头。
方案二:显式配置OPTIONS方法的CORS规则
当接口配置了自定义授权器(authorizer)时,Serverless自动生成的OPTIONS预请求可能无法正确继承主方法的CORS配置。此时可以单独为OPTIONS方法添加完整的CORS配置:
# 单独配置OPTIONS方法 - http: path: /path method: options cors: origins: - http://localhost:8080 - http://localhost:8081 headers: ${self:custom.allowedHeaders} allowCredentials: true # 原POST方法配置 - http: path: /path method: post authorizer: ${self:custom.authorizer} cors: origins: - http://localhost:8080 - http://localhost:8081 headers: ${self:custom.allowedHeaders} allowCredentials: true
这种方式会强制为OPTIONS请求生成包含Access-Control-Allow-Credentials: true的响应头。
方案三:检查自定义Header变量格式
确保custom.allowedHeaders的定义符合规范,建议在serverless.yml的custom部分用字符串格式定义:
custom: allowedHeaders: "Content-Type,Authorization,language"
注意Authorization首字母大写(HTTP头字段通常采用驼峰命名),避免因格式问题导致CORS规则解析异常。
内容的提问来源于stack exchange,提问作者Naisargi Trivedi
相关产品推荐
相关产品推荐

