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

为何用Middy与Serverless设置Access-Control-Allow-Headers时headers选项无效?

问题:AWS API Gateway + Serverless 中Middy CORS配置无效,Serverless.yml配置生效的原因

遇到的CORS错误:

Access to fetch at 'https://example.com/shop' from origin 'https://otherexample.com' has been blocked by CORS policy: Request header field shop is not allowed by Access-Control-Allow-Headers in preflight response.

尝试使用Middy的cors()中间件配置但无效:

const handler = middy(async (event, context) => {
  // ...
})

handler.use(cors({
  headers: 'Content-Type, shop'
}));

module.exports.handler = handler;

而Serverless.yml中的CORS配置却能正常生效:

findShop:
  handler: src/routes/findShop.handler
  events:
    - http:
        path: /shop
        method: post
        cors:
          origin: '*'
          headers:
            - Content-Type
            - shop

原因分析

  • 预检请求的处理主体差异:API Gateway的CORS预检OPTIONS请求是由网关直接处理的,不会触发你的Lambda函数。Middy的cors()中间件是在Lambda层面设置响应头,完全触及不到预检请求的处理逻辑,自然无效。而Serverless.yml里的cors配置是直接告知API Gateway,让网关在预检响应中返回允许的shop头,所以能通过预检。

  • Middy cors中间件的作用范围:Middy的cors()仅能处理**实际业务请求(比如你的POST请求)**的响应头,无法干预API Gateway的预检规则配置。只有当请求属于无需预检的简单请求时,Middy的配置才可能生效,但你的请求携带了自定义shop头,属于非简单请求,必须先通过预检,这一步只能靠API Gateway层面的配置。

  • 文档理解偏差:@middy/http-cors文档中提到的headers参数,确实用于设置Access-Control-Allow-Headers响应头,但这个头是附加在Lambda返回的实际请求响应里的,和API Gateway的预检响应无关。预检都没通过,实际请求根本无法发送,Middy的配置也就没机会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:25:12