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

带请求头调用Lambda函数遇CORS错误排查求助

解决Serverless HTTP API + Lambda的CORS问题

核心问题排查

你遇到的问题核心是两个冲突点:

  1. 携带Authorization这类自定义请求头的请求会触发浏览器预检OPTIONS请求,若预检响应不符合规则就会抛出CORS错误。
  2. 当设置Access-Control-Allow-Credentials: true时,浏览器禁止Access-Control-Allow-Origin使用通配符*,必须指定前端的具体域名。

1. 修正Serverless.yml的HTTP API CORS配置

HTTP API的CORS配置逻辑和传统REST API不同,需在httpApi块下单独配置(控制台手动修改的配置会被sls deploy覆盖):

service: your-service-name

provider:
  name: aws
  runtime: nodejs18.x
  region: us-east-1

httpApi:
  cors:
    allowedOrigins:
      - https://your-react-app-domain.com # 替换为你的前端实际域名,不能用*
    allowedHeaders:
      - Content-Type
      - Authorization # 必须明确允许自定义请求头
    allowedMethods:
      - GET
      - POST
      - OPTIONS
      - PUT
      - DELETE
    allowCredentials: true # 必须和具体域名配合使用,不能搭配*

functions:
  yourFunction:
    handler: handler.yourFunction
    events:
      - httpApi:
          path: /your-path
          method: post

2. 调整Lambda响应头的动态设置

不要硬编码Access-Control-Allow-Origin: *,需动态获取请求的Origin头返回,同时确保预检请求和实际请求都返回合规头:

exports.yourFunction = async (event) => {
  // 处理预检OPTIONS请求
  if (event.requestContext.http.method === 'OPTIONS') {
    return {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': event.headers.origin || 'https://your-react-app-domain.com',
        'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,PUT,DELETE',
        'Access-Control-Allow-Headers': 'Content-Type,Authorization',
        'Access-Control-Allow-Credentials': true
      },
      body: JSON.stringify('OK')
    };
  }

  // 处理实际业务请求
  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': event.headers.origin || 'https://your-react-app-domain.com',
      'Access-Control-Allow-Credentials': true,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ message: '请求成功' })
  };
  return response;
};

3. 验证预检请求响应

部署后用curl测试OPTIONS请求,确认响应头符合要求:

curl -X OPTIONS \
  -H "Origin: https://your-react-app-domain.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: Authorization,Content-Type" \
  https://your-api-endpoint.execute-api.us-east-1.amazonaws.com/your-path

返回的响应头必须包含:

  • Access-Control-Allow-Origin: https://your-react-app-domain.com(和请求的Origin完全一致)
  • Access-Control-Allow-Credentials: true
  • Access-Control-Allow-Headers: Content-Type,Authorization

4. 清除浏览器缓存

浏览器可能会缓存旧的CORS响应规则,测试前先清除缓存或用无痕模式打开前端页面。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:55:21