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

NestJS部署Vercel时仅POST请求出现CORS跨域问题求助

问题:SWR发起POST请求时遭遇CORS错误,GET请求正常

问题场景

GET请求可正常运行,但使用SWR发起POST请求向Firebase提交数据并更新状态时失败,相关代码如下:

SWR请求代码

const item = await fetcher.POST(`/jobs?user_id=${user.id}`, _job)
mutate(item)

Fetcher配置

fetcher.POST = (
  url,
  data,
  headers = {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json'
  }
) => {
  return fetcher(HOST + url, {
    method: 'POST',
    headers,
    body: JSON.stringify(data)
  })
}

控制台报错信息

Access to fetch at 'https://example-api.vercel.app/v1/jobs?user_id=8JKY8PRM5APwIz1' from origin 'https://workshop-4i8ymvm1s.vercel.app' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

NestJS无服务器函数的CORS配置

已在index.ts和main.ts中配置CORS,代码如下:

const app = await NestFactory.create(AppModule, {
  snapshot: true,
  logger: new Logg(),
  cors: true
});

以及:

app.enableCors({
  allowedHeaders: '*',
  origin: '*',
  credentials: false,
});

补充说明

Postman测试请求正常,但浏览器环境下无法运行,已查阅文档未找到可行方案。


排查与解决步骤

  1. 移除请求头中的Access-Control-Allow-Origin
    该头是服务器返回给浏览器的响应头,不是前端请求时需要发送的。前端请求携带这个头会触发额外的预检请求,反而可能导致CORS验证失败。修改fetcher配置:

    fetcher.POST = (
      url,
      data,
      headers = {
        'Content-Type': 'application/json'
      }
    ) => {
      return fetcher(HOST + url, {
        method: 'POST',
        headers,
        body: JSON.stringify(data)
      })
    }
    
  2. 解决NestJS CORS配置冲突
    你同时使用了NestFactory.create时的cors: true和app.enableCors(),两种配置可能冲突。建议只保留一种方式,推荐使用app.enableCors()的详细配置:

    // 移除create时的cors: true,只保留下面的配置
    const app = await NestFactory.create(AppModule, {
      snapshot: true,
      logger: new Logg(),
    });
    
    app.enableCors({
      origin: '*',
      methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
      allowedHeaders: '*',
      credentials: false,
    });
    
  3. 配置Vercel无服务器函数的CORS规则
    由于部署在Vercel,需额外配置平台层面的CORS规则。在项目根目录创建vercel.json文件,添加以下内容:

    {
      "functions": {
        "api/**/*.ts": {
          "cors": {
            "origin": "*",
            "methods": ["GET", "POST", "OPTIONS"],
            "allowedHeaders": ["Content-Type"]
          }
        }
      }
    }
    
  4. 验证预检请求(OPTIONS)的响应
    浏览器发送POST前会先发送OPTIONS预检请求,需确保服务器能正确响应并返回Access-Control-Allow-Origin等必要头。可通过浏览器开发者工具的Network面板查看OPTIONS请求的响应头,确认是否包含正确的CORS配置。

内容的提问来源于stack exchange,提问作者Harry-Joe Valente

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:45:15