NextJs CORS 问题 [英] NextJs CORS issue
问题描述
我在 www.example.com 的 Vercel 上有一个 Next.js 应用程序,它需要与托管在 api.example.com 上的不同服务器上的后端 .NET Core Web API..NET 核心 web api 已配置为允许 CORS,但我的 Next.js 一直抱怨当我使用 AXIOS 获取数据时无法显示数据,因为响应缺少 allow-cors 标头:
I have a Next.js app hosted on Vercel at www.example.com, which needs to communicate with a backend .NET Core Web API hosted on a different server at api.example.com. The .NET core web api has been configured to allow CORS but my Next.js keeps complaining that data cannot be displayed when I use AXIOS to fetch data because the response lacks allow-cors headers:
从源http://www.example.com"访问https://api.example.com"上的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上没有Access-Control-Allow-Origin"标头
Access to XMLHttpRequest at 'https://api.example.com' from origin 'http://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
当我使用 npm run dev
在本地运行它时它工作正常,但是当我构建它然后运行它时它不起作用 npm run start
It works fine when I run it locally using npm run dev
, but doesn't work when I build it and then run npm run start
有人知道如何解决生产中的 cors 问题吗?
Does anyone know how to fix the cors issue in production?
推荐答案
我找到了解决方案 这里:
基本上我只需要在根目录下添加一个next.config.js文件并添加以下内容:
Basically, I just need to add a next.config.js file in the root directory and add the following:
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://api.example.com/:path*',
},
]
},
};
这篇关于NextJs CORS 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!