启用 CORS 在 Vercel 上部署的 Next.js 中不起作用

问题描述 投票:0回答:1

我正在尝试在 Vercel 上使用 Next.js 部署单页应用程序。

我有一个 POST 和一个 GET 请求,它已部署,但我无法向 API 发出任何请求。它一直给我这个错误:

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.

我已经添加了 Vercel 网站上有关如何在

vercel.json
next.config.mjs
中启用 cors 的代码,但它仍然无法正常工作。 (来源:https://vercel.com/guides/how-to-enable-cors

我的实际

next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
  async headers() {
    return [
        {
            // matching all API routes
            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" }
      ]
    }
  ]
}

我也让他们在这里的值

{ "key": "Access-Control-Allow-Origin", "value": "*" },
是“http://localhost:3000”,它没有效果。

我还将 fetch url 更改为环境变量,并从一些 Stack Overflow 线程中使用它,但仍然没有任何结果。

NEXT_PUBLIC_BASE_URL = http://localhost:3000

我的两个获取请求:

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);
    }
const getConfessions = async () => {
    const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/`);
    const confessions = await res.json();
    setConfessions(confessions.reverse());
    return confessions;
  }

这是我在 GitHub 上的存储库(如果有帮助的话):https://github.com/letmeeatbrioche/confessions

next.js cors vercel
1个回答
0
投票

意识到是我的获取网址导致了问题。我将其设置为“http://localhost:3000/api/”,但是当我将其更改为相对路径“../api/”时,它起作用了。

© www.soinside.com 2019 - 2024. All rights reserved.