如何在next.js中使用package.json中的代理?
How to use proxy in package.json in next.js?
在 create-react-app
(s) 中可以像这样在 package.json
中指定代理:
{
"name": "client",
"version": "0.1.0",
"private": true,
>>> "proxy": "http://localhost:5000", <<<
"dependencies": {
...
},
"scripts": {
...
},
"eslintConfig": {
...
},
"browserslist": {
"production": [
...
],
"development": [
...
]
}
}
在 next.js 应用程序中执行相同的操作没有任何效果。有解决方法吗?当开始停用旧前端但仍在使用后端时,这将特别有用。
尝试使用 npm 中的这个包为 Express 创建 Node.js 代理:http-proxy-middleware
然后您可以配置目标选项以将请求代理到正确的域:
const proxy = require('http-proxy-middleware')
app.use('/api', proxy({ target: 'http://localhost:5000', changeOrigin: true }));
在此处查找 next.js 的类似包裹:next-http-proxy-middleware
另一种方法是使用重写配置:
https://nextjs.org/docs/api-reference/next.config.js/rewrites
module.exports = {
async rewrites() {
return [
{
source: '/api/:slug*',
destination: 'http://www.example.com/api/:slug*'
},
]
},
}
在 create-react-app
(s) 中可以像这样在 package.json
中指定代理:
{
"name": "client",
"version": "0.1.0",
"private": true,
>>> "proxy": "http://localhost:5000", <<<
"dependencies": {
...
},
"scripts": {
...
},
"eslintConfig": {
...
},
"browserslist": {
"production": [
...
],
"development": [
...
]
}
}
在 next.js 应用程序中执行相同的操作没有任何效果。有解决方法吗?当开始停用旧前端但仍在使用后端时,这将特别有用。
尝试使用 npm 中的这个包为 Express 创建 Node.js 代理:http-proxy-middleware
然后您可以配置目标选项以将请求代理到正确的域:
const proxy = require('http-proxy-middleware')
app.use('/api', proxy({ target: 'http://localhost:5000', changeOrigin: true }));
在此处查找 next.js 的类似包裹:next-http-proxy-middleware
另一种方法是使用重写配置: https://nextjs.org/docs/api-reference/next.config.js/rewrites
module.exports = {
async rewrites() {
return [
{
source: '/api/:slug*',
destination: 'http://www.example.com/api/:slug*'
},
]
},
}