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

仅配置默认端点的Serverless应用无法开启CORS问题求助

AWS Serverless 接口跨域CORS预请求报错解决方案

报错本质是浏览器发起的OPTIONS类型CORS预请求未被服务端正确响应200状态码,同时缺少必要的跨域响应头。Postman不会自动触发CORS预校验,因此请求可以正常执行。

第一步:修正Serverless配置

你当前同时配置了http(REST API)和httpApi(HTTP API)两类事件,会生成两个不同的API网关端点,建议先确认实际使用的API类型,删除冗余配置后添加对应的CORS规则:

如果你使用REST API(http事件)

functions:
  connect-api:
    handler: api.handler
    name: something
    description: Connect api
    timeout: 29
    events:
      - http:
          path: /{any+} 
          method: ANY
          # 新增CORS配置
          cors:
            origin: '*' # 本地开发可填http://localhost:你的前端端口,生产环境替换为正式前端域名
            allowHeaders: '*'
            allowMethods: ['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE', 'PATCH']

如果你使用HTTP API(httpApi事件)

CORS规则需要配置在provider全局层级:

provider:
  name: aws
  runtime: nodejs18.x # 替换为你实际使用的运行时版本
  # 新增全局HTTP API CORS配置
  httpApi:
    cors:
      allowedOrigins: '*' # 同上,生产环境替换为具体域名
      allowedHeaders: '*'
      allowedMethods: ['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE', 'PATCH']

functions:
  connect-api:
    handler: api.handler
    name: something
    description: Connect api
    timeout: 29
    events:
      - httpApi: '*'

第二步:代码层处理OPTIONS预请求

如果你的Lambda使用代理集成模式,需要在业务代码中主动响应OPTIONS请求:

// Node.js 示例,其他语言逻辑一致
module.exports.handler = async (event) => {
  // 优先处理CORS预请求
  if (event.httpMethod === 'OPTIONS') {
    return {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'OPTIONS,GET,POST,PUT,DELETE,PATCH',
        'Access-Control-Allow-Headers': '*'
      },
      body: ''
    }
  }

  // 原有业务逻辑
  // ...
}

第三步:验证配置是否生效

部署完成后执行curl命令直接测试预请求:
curl -X OPTIONS 你的API完整请求地址 -v
检查返回的状态码是否为200,响应头中是否包含上述Access-Control开头的跨域头,确认正常后再用前端发起请求测试。

内容的提问来源于stack exchange,提问作者Óscar Contreras

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:36:03