在 Next.js + React 項目中解決本地開發跨域問題,可以通過以下幾種方式實現代理請求:
方案1:使用 Next.js 內置的 Rewrites 功能(推薦)
1. 修改 next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {async rewrites() {return [{source: '/api/:path*', // 匹配所有/api開頭的請求destination: 'http://localhost:5000/api/:path*', // 代理目標地址},{source: '/uploads/:path*',destination: 'http://localhost:5000/uploads/:path*',}]}
}module.exports = nextConfig
2. 前端直接請求相對路徑
// 直接請求 /api/users(會被自動代理到 http://localhost:5000/api/users)
fetch('/api/users').then(res => res.json()).then(data => console.log(data))
優點:
- 零配置前端代碼
- 無跨域問題(瀏覽器看到的是同源請求)
- 支持所有 HTTP 方法
方案2:自定義 API 路由(Next.js Serverless Functions)
1. 創建代理 API 路由
// pages/api/proxy/[...path].js
export default async function handler(req, res) {const { path } = req.queryconst targetUrl = `http://localhost:5000/${path.join('/')}`try {const response = await fetch(targetUrl, {method: req.method,headers: req.headers,body: req.method !== 'GET' ? JSON.stringify(req.body) : undefined})const data = await response.json()res.status(response.status).json(data)} catch (error) {res.status(500).json({ error: 'Proxy error' })}
}
2. 前端調用
fetch('/api/proxy/users').then(res => res.json()).then(data => console.log(data))
適用場景:
- 需要自定義請求處理邏輯
- 后端接口需要鑒權等復雜處理
方案3:配置開發服務器代理(create-next-app 自帶)
1. 修改 package.json
{"proxy": "http://localhost:5000"
}
注意:Next.js 9.5+ 已移除此功能,需使用方案1或方案2
方案4:使用 http-proxy-middleware
1. 安裝依賴
npm install http-proxy-middleware
2. 創建 src/setupProxy.js
(需 react-scripts)
const { createProxyMiddleware } = require('http-proxy-middleware')module.exports = function(app) {app.use('/api',createProxyMiddleware({target: 'http://localhost:5000',changeOrigin: true,pathRewrite: { '^/api': '' }}))
}
適用場景:
- 與 Express 等 Node.js 服務集成開發時
方案5:CORS 配置(需后端配合)
如果必須直接請求后端接口,讓后端添加:
// Express 示例
app.use((req, res, next) => {res.header('Access-Control-Allow-Origin', 'http://localhost:3000')res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE')res.header('Access-Control-Allow-Headers', 'Content-Type')next()
})
各方案對比
方案 | 是否需要改前端代碼 | 是否需要改后端 | 適用場景 |
---|---|---|---|
Next.js Rewrites | ? 不需要 | ? 不需要 | 簡單代理 |
API 路由 | ? 不需要 | ? 不需要 | 復雜代理邏輯 |
http-proxy-middleware | ? 不需要 | ? 不需要 | 傳統 React 項目遷移 |
CORS | ? 不需要 | ? 需要 | 前后端分離部署 |
最佳實踐建議
- 開發環境:使用方案1(Rewrites),配置最簡單
- 生產環境:
- 同域部署:無需代理
- 跨域部署:方案2(API路由)或讓后端開啟CORS
- 復雜場景:結合方案1和方案2,部分接口走rewrites,特殊接口走API路由
調試技巧
-
查看實際請求:
// 在next.config.js的rewrites中添加日志 console.log('Proxying:', source, '→', destination)
-
使用
curl
測試:curl -v http://localhost:3000/api/users
-
檢查Network面板:
- 確保請求顯示為
localhost:3000
發起 - 查看響應頭是否包含
x-middleware-rewrite
- 確保請求顯示為
通過以上方法,可以徹底解決本地開發時的跨域問題,同時保持生產環境的兼容性。