我有一個託管在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 問題嗎?
如果你想在
nextjs
中使用cors
函式庫,我為其建立了一個函式庫nextjs-cors
。https://www.npmjs.com/nextjs-cors
https://github.com/yonycalsin/nextjs-cors
#我在這裡找到了解決方案:
基本上,我只需要在根目錄中新增一個 next.config.js 檔案並新增以下內容: