在 Next.js + React 项目中解决本地开发跨域问题,可以通过以下几种方式实现代理请求:
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
// 直接请求 /api/users(会被自动代理到 http://localhost:5000/api/users)
fetch('/api/users')
.then(res => res.json())
.then(data => console.log(data))
// pages/api/proxy/[...path].js
export default async function handler(req, res) {
const { path } = req.query
const 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' })
}
}
fetch('/api/proxy/users')
.then(res => res.json())
.then(data => console.log(data))
package.json
{
"proxy": "http://localhost:5000"
}
注意:Next.js 9.5+ 已移除此功能,需使用方案1或方案2
npm install http-proxy-middleware
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 示例
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 | ❌ 不需要 | ✅ 需要 | 前后端分离部署 |
查看实际请求:
// 在next.config.js的rewrites中添加日志
console.log('Proxying:', source, '→', destination)
使用 curl
测试:
curl -v http://localhost:3000/api/users
检查Network面板:
localhost:3000
发起x-middleware-rewrite
通过以上方法,可以彻底解决本地开发时的跨域问题,同时保持生产环境的兼容性。