Vercel 上 Nextjs 应用程序中的 CORS

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

我目前正在使用我的第一个更大的 NextJS 应用程序,并且遇到了经典的 CORS 问题。

我有一个后端,托管在不同的服务器/url 上,我从这个后端获取 json 数据。 我用 NextJS 编写的前端部署在 Vercel 上。

我确实知道,我必须在后端和前端都启用 CORS,在我的本地主机开发中,一切都工作正常(甚至从后端获取数据)

我已经按照本指南进行操作:https://vercel.com/knowledge/how-to-enable-cors,在我的 NextJS 应用程序中启用 CORS。我修改了 nextjs 配置:

module.exports = {
  async headers() {
    return [
      {
        source: "/.*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
          { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,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" },
        ]
      }
    ]
  }
};

但是,在 vercel 上部署应用程序时,我收到以下错误:

Access to fetch at 'https://<my-censored-backend-url>' from origin 'https://<my-frontend-url>.vercel.app' 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.

在我的后端(用 Rails 编写)中,我已经在 vercel 上配置了我的前端以允许使用 CORS。 我有什么遗漏的吗?

你们有 CORS 和从不同服务器获取 NextJS 数据的经验吗? 我正在使用 getStaticProps、getServerSideProps 和 SWR 来获取。

如有任何帮助,我们将不胜感激

javascript reactjs cors fetch next.js
1个回答
0
投票

我认为 NextJS 有一个奇怪的问题,有时它只是随机抛出

CORS
错误。

就我而言,如果 URL 错误,则会抛出此

CORS
错误。 例如,我使用“https://localhost:3000”,然后它会抛出 CORS 错误。它适用于“http://localhost:3000”。

所以我的建议是仔细检查您正在使用的 URL。 另外,请确保不要包含尾部斜杠,例如“http://localhost:3000/”可能不起作用。

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