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

使用Serverless Component部署Express应用时如何解决CORS缺失允许源错误

解决API Gateway+Serverless Components部署Express API的CORS问题

问题现象

React前端调用部署在API Gateway上的Typescript Express API时,出现CORS错误:

Access to XMLHttpRequest at 'https://randomId.execute-api.ap-southeast-2.amazonaws.com/userLoginSignup' from origin 'https://www.tueshey.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

本地调试时OPTIONS请求正常返回Access-Control-Allow-Origin头部,但部署后该头部缺失。

当前Express的CORS配置:

...
const app = express();

// CORS
const allowlist = ['https://www.tueshey.com'];
const options: cors.CorsOptions = {
  origin: allowlist,
};
app.use(cors(options));
...

解决步骤

  • 配置API Gateway层面的CORS规则
    用Serverless Components部署到API Gateway时,preflight(OPTIONS)请求可能被API Gateway直接拦截处理,不会转发到Express应用。需要在Serverless配置中显式开启CORS:
    示例配置(根据你使用的Serverless Component类型调整字段):

    inputs:
      api:
        cors:
          origins:
            - https://www.tueshey.com
          headers:
            - Content-Type
            - X-Amz-Date
            - Authorization
            - X-Api-Key
            - X-Amz-Security-Token
            - X-Amz-User-Agent
          methods:
            - GET
            - POST
            - OPTIONS
    
  • 调整Express的CORS配置
    确保配置能覆盖实际需求,比如支持认证信息传递、显式暴露响应头:

    const options: cors.CorsOptions = {
      origin: 'https://www.tueshey.com',
      credentials: true, // 若前端需传递cookie或认证信息则开启
      allowedHeaders: ['Content-Type', 'Authorization'],
      exposedHeaders: ['Custom-Header'], // 若前端需读取自定义响应头则添加
      methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
    };
    app.use(cors(options));
    

    注意:使用数组形式origin时,需保证请求origin与数组值严格匹配(含协议、域名、端口)。

  • 验证API Gateway的OPTIONS方法配置
    部署后登录AWS控制台进入API Gateway,检查对应API的OPTIONS方法是否存在,且集成响应中包含Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers等必要头部,缺失则手动添加或重新部署Serverless配置。

  • 清除浏览器缓存
    浏览器可能缓存旧的CORS响应头,测试前清除缓存或使用隐身模式访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:40:29