NextJs CORS問題
P粉919464207
P粉919464207 2023-08-29 12:57:35
0
2
496

我有一個託管在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 標頭:

從來源「http://www.example.com」存取「https://api.example.com」處的XMLHttpRequest 已被CORS 策略阻止:對預檢請求的回應未透過存取控制檢查:請求的資源上不存在「Access-Control-Allow-Origin」標頭

當我使用npm run dev 在本地運行它時,它工作正常,但當我構建它然後運行npm run start

;

有人知道如何解決生產中的 cors 問題嗎?

P粉919464207
P粉919464207

全部回覆 (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*', }, ] }, };
      最新下載
      更多>
      網站特效
      網站源碼
      網站素材
      前端模板
      關於我們 免責聲明 Sitemap
      PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!