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

使用Serverless Framework v4部署AWS API的CORS问题求助

解决AWS API Gateway + Serverless Framework的CORS问题

第一步:移除前端错误的请求头

你在Axios配置里错误地添加了后端响应专属的头字段(Access-Control-Allow-Origin和Access-Control-Allow-Headers),这些字段不该出现在前端请求中,直接删除:

const api = axios.create({
  baseURL: 'https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `${authStore.tokenType} ${authStore.accessToken}`
  },
});

第二步:完善Serverless.yml的CORS配置

默认的cors: true不会自动允许Authorization头,而你的请求携带了该头,导致预飞行检查失败。需要明确配置允许的Headers、Origin和凭证:

functions:
  authCreateUserFromAdminHandler:
    handler: src/modules/Auth/handlers/createUserFromAdminHandler.handler
    events:
      - http:
          path: auth/createUserFromAdmin
          method: post
          cors:
            origin: 'http://localhost:5173' # 匹配你的前端开发地址
            headers:
              - Content-Type
              - Authorization
            allowCredentials: true

第三步:调整Lambda响应头,避免通配符与凭证冲突

当Access-Control-Allow-Credentials设为true时,Access-Control-Allow-Origin不能使用*,必须指定具体Origin,建议动态获取请求头中的Origin以适配不同环境:

export const handler = async (event: APIGatewayEvent, context: Context, callback: Function) => {
  /* ... process information */
  const allowedOrigin = event.headers.Origin || 'http://localhost:5173';
  const headers = {
    'Access-Control-Allow-Origin': allowedOrigin,
    'Access-Control-Allow-Credentials': true,
    'Access-Control-Allow-Headers': 'Content-Type, Authorization'
  }
  const response = {
    statusCode: 201,
    headers,
    body: JSON.stringify({ OK: true })
  }
  return response; // 确保返回响应对象,你的原代码遗漏了这一步
}

第四步:重新部署Serverless服务

修改配置后执行serverless deploy,确保新的CORS规则生效。

内容的提问来源于stack exchange,提问作者Lucas David Ferrero

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 23:11:14