NextJs CORS-Problem
P粉919464207
P粉919464207 2023-08-29 12:57:35
0
2
519
<p>Ich habe eine Next.js-Anwendung, die auf Vercel (www.example.com) gehostet wird, für deren Kommunikation ein Backend erforderlich ist, das auf einem anderen Server als api.example.com (api.example.com) gehostet wird . Die .NET Core-Web-API ist so konfiguriert, dass sie CORS zulässt, aber mein Next.js beschwert sich ständig darüber, dass es die Daten nicht anzeigen kann, wenn ich sie mit AXIOS erhalte, weil in der Antwort der Allow-Cors-Header fehlt: </p> <blockquote> <p>Der Zugriff auf XMLHttpRequest unter „https://api.example.com“ vom Ursprung „http://www.example.com“ wird durch die CORS-Richtlinie blockiert: Antwort auf die Preflight-Anfrage ist bei der Zugriffskontrollprüfung fehlgeschlagen: Der „Access Der Header „-Control-Allow-Origin“ ist auf der angeforderten Ressource nicht vorhanden</p> </blockquote> <p>Wenn ich es lokal mit <code>npm run dev</code> ausführe, funktioniert es einwandfrei, aber wenn ich es erstelle und dann <code>npm run start</code></p> ausführe; <p>Weiß jemand, wie man CORS-Probleme in der Produktion lösen kann? </p>
P粉919464207
P粉919464207

Antworte allen(2)
P粉438918323

如果你想在 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!' });
}
P粉044526217

我在此处找到了解决方案:

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

// next.config.js
module.exports = {
    async rewrites() {
        return [
          {
            source: '/api/:path*',
            destination: 'https://api.example.com/:path*',
          },
        ]
      },
  };
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!