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

AWS Serverless部署中带凭证的CORS预检请求异常解决咨询

解决AWS Serverless Lambda的CORS预检失败问题

我来帮你搞定这个CORS预检的坑——你已经在Lambda里做了Origin校验,但问题出在API Gateway的预检请求(OPTIONS)没有被正确处理,导致浏览器直接拦截了后续的POST请求。下面是一步步的解决方案:

第一步:修正Serverless YAML的CORS配置

你的原配置只针对POST请求设置了CORS,但API Gateway需要明确允许OPTIONS方法,并且让预检请求能拿到正确的响应头。修改你的Serverless配置如下:

functions:
  publish:
    handler: lambda.publish
    events:
      - http:
          method: post
          path: publish
          cors:
            origin: '*'  # 让API Gateway先放行预检,实际校验在Lambda里做
            allowCredentials: true
            allowHeaders:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
            allowMethods:
              - POST
              - OPTIONS

这里把origin设为*是为了让API Gateway不会拦截预检请求,真正的域名权限控制依然由你的Lambda代码来做,不用担心安全问题。

第二步:在Lambda中专门处理OPTIONS预检请求

浏览器发送的CORS预检是OPTIONS方法,你需要在Lambda里优先处理这个请求,返回符合要求的响应头。修改你的Lambda代码:

const ALLOWED_ORIGINS = [
  'http://localhost:3001',
  'https://staging.company.com.au',
  'https://blaze-staging.company.com.au',
  'https://www.company.com.au',
  'https://blaze.company.com.au',
  'https://direct.company.com.au',
];

exports.publish = (event, context, callback) => {
  // 优先处理OPTIONS预检请求
  if (event.httpMethod === 'OPTIONS') {
    const origin = event.headers.origin;
    const headers = ALLOWED_ORIGINS.includes(origin) 
      ? {
          'Access-Control-Allow-Origin': origin,
          'Access-Control-Allow-Credentials': true,
          'Access-Control-Allow-Headers': 'Content-Type',
          'Access-Control-Allow-Methods': 'POST, OPTIONS'
        }
      : {
          'Access-Control-Allow-Origin': 'http://localhost:3001',
          'Access-Control-Allow-Credentials': true,
          'Access-Control-Allow-Headers': 'Content-Type',
          'Access-Control-Allow-Methods': 'POST, OPTIONS'
        };

    callback(null, {
      statusCode: 200,
      headers,
      body: ''
    });
    return;
  }

  // 处理正常的POST请求逻辑
  const origin = event.headers.origin;
  const headers = ALLOWED_ORIGINS.includes(origin)
    ? {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': origin,
        'Access-Control-Allow-Credentials': true,
      }
    : {
        'Access-Control-Allow-Origin': 'http://localhost:3001',
      };

  const response = {
    statusCode: 200,
    headers,
    body: JSON.stringify({ message: 'Successfully published the message.' }),
  };
  callback(null, response);
};

这样修改后,预检请求会得到正确的响应头,浏览器就会继续发送POST请求了。

第三步:重新部署服务

执行以下命令更新你的Serverless部署:

serverless deploy

为什么之前会失败?

你之前的配置里,API Gateway没有为OPTIONS请求配置正确的CORS响应头,导致浏览器的预检请求直接返回403。虽然你在Lambda里处理了POST请求的Origin,但预检请求根本没到达Lambda就被API Gateway拦截了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:20:18