<p>我有一个托管在 Vercel(www.example.com)上的 Next.js 应用程序,它需要与托管在 api.example.com(api.example.com)的不同服务器上的后端 .NET Core Web API 进行通信。
.NET core Web api 已配置为允许 CORS,但我的 Next.js 不断抱怨当我使用 AXIOS 获取数据时无法显示数据,因为响应缺少allow-cors 标头:</p>
<blockquote>
<p>从源“http://www.example.com”访问“https://api.example.com”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头</p>
</blockquote>
<p>当我使用 <code>npm run dev</code> 在本地运行它时,它工作正常,但当我构建它然后运行 <code>npm run start</code></p>
<p>有人知道如何解决生产中的 cors 问题吗?</p>
如果你想在
nextjs中使用cors库,我为其创建了一个库nextjs-cors。https://www.npmjs.com/nextjs-cors
https://github.com/yonycalsin/nextjs-cors
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!' }); }我在此处找到了解决方案:
基本上,我只需要在根目录中添加一个 next.config.js 文件并添加以下内容:
// next.config.js module.exports = { async rewrites() { return [ { source: '/api/:path*', destination: 'https://api.example.com/:path*', }, ] }, };