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

Next.js部署Vercel后CORS配置无效问题求助

问题:Vercel部署Next.js应用后API请求触发CORS错误

错误信息

Access to fetch at 'http://localhost:3000/api/' from origin [...] has been blocked by CORS policy: 
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.

已配置的CORS规则

next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
  async headers() {
    return [
        {
            // 匹配所有API路由
            source: "\/api\/:path*",
            headers: [
                { key: "Access-Control-Allow-Credentials", value: "true" },
                { key: "Access-Control-Allow-Origin", value: "*" },
                { key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
                { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
            ]
        }
    ]
}
};

export default nextConfig;

vercel.json

{
  "headers": [
    {
      "source": "\/api\/(.*)",
      "headers": [
        { "key": "Access-Control-Allow-Credentials", "value": "true" },
        { "key": "Access-Control-Allow-Origin", "value": "*" },
        { "key": "Access-Control-Allow-Methods", "value": "GET,DELETE,PATCH,POST,PUT" },
        { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
      ]
    }
  ]
}

已尝试的排查操作

  • 将Access-Control-Allow-Origin值改为"http://localhost:3000",问题未解决
  • 使用环境变量NEXT_PUBLIC_BASE_URL = http://localhost:3000拼接请求URL,CORS错误依然存在

相关请求代码

POST请求

try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        cache: "no-store",
        body: JSON.stringify({ text }),
      })
      console.log('Successfully uploaded confession!: ', text);
      setSubmitted(!submitted);
      setText('');
    } catch (error) {
      console.error("Error posting confession from home page:", error);
    }

GET请求

const getConfessions = async () => {
    const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/`);
    const confessions = await res.json();
    setConfessions(confessions.reverse());
    return confessions;
  }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 10:42:13