【问题标题】:CORS in Nextjs Application on VercelVercel 上 Nextjs 应用程序中的 CORS
【发布时间】:2021-04-10 11:39:01
【问题描述】:

我目前正在使用我的第一个更大的 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 进行获取。

任何帮助将不胜感激

【问题讨论】:

  • CORS 标头对客户端(HTTP request 端)完全没有任何作用。使用您的浏览器网络调试选项卡查看从您的服务器目标返回的标头。
  • 所以你认为错误的原因一定来自后端?有趣的是,通过 getStaticProps 的数据可以工作,但不能通过客户端调用
  • 您在浏览器的开发工具中的客户端请求中看到'Access-Control-Allow-Origin' 标头吗?
  • 不,很遗憾没有标题
  • 那么,每个客户端请求也应该明确包含标头?目前我在 nextjs.config 中设置了标头难道 CORS 标头仅与响应相关吗?

标签: javascript reactjs cors fetch next.js


【解决方案1】:

您可以使用以下配置将 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,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" }
      ]
    }
  ]
}

您可以从How can I enable CORS on Vercel?找到更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 2023-03-12
    • 2022-07-25
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2022-11-11
    • 2021-10-28
    相关资源
    最近更新 更多