NextJs CORS 问题

新手上路,请多包涵

我在 www.example.com 的 Vercel 上托管了一个 Next.js 应用程序,它需要与托管在 api.example.com 的不同服务器上的后端 .NET Core Web API 进行通信。 .NET 核心 web api 已配置为允许 CORS,但我的 Next.js 一直抱怨当我使用 AXIOS 获取数据时无法显示数据,因为响应缺少 allow-cors 标头:

从源“http://www.example.com”访问“https://api.example.com”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问” -Control-Allow-Origin’ 标头出现在请求的资源上

当我使用 npm run dev 在本地运行它时它工作正常,但是当我构建它然后运行它时 npm run start

有谁知道如何解决生产中的cors问题?

原文由 Yoope 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

我在 这里 找到了解决方案:

基本上,我只需要在根目录下添加一个 next.config.js 文件并添加以下内容:

 // next.config.js
module.exports = {
    async rewrites() {
        return [
          {
            source: '/api/:path*',
            destination: 'https://api.example.com/:path*',
          },
        ]
      },
  };

原文由 Yoope 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你想在 --- 中使用 --- nextjs cors 库,我为它创建了一个库 nextjs-cors

https://www.npmjs.com/nextjs-cors

https://github.com/yonycalsin/nextjs-cors

页面/api/whoami.{ts,js}

 import NextCors from 'nextjs-cors';

async function handler(req, res) {
   // Run the cors middleware
   // nextjs-cors uses the cors package, so we invite you to check the documentation https://github.com/expressjs/cors
   await NextCors(req, res, {
      // Options
      methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
      origin: '*',
      optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
   });

   // Rest of the API logic
   res.json({ message: 'Hello NextJs Cors!' });
}

原文由 Yony Calsin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题