[英]How to use proxy in package.json in next.js?
In create-react-app
(s) it is possible to specify a proxy in the package.json
like this:在
create-react-app
(s) 中,可以像这样在package.json
中指定一个代理:
{
"name": "client",
"version": "0.1.0",
"private": true,
>>> "proxy": "http://localhost:5000", <<<
"dependencies": {
...
},
"scripts": {
...
},
"eslintConfig": {
...
},
"browserslist": {
"production": [
...
],
"development": [
...
]
}
}
Doing the same in a next.js app has no effect whatsoever.在 next.js 应用程序中执行相同操作没有任何效果。 Is there a workaround?
有解决方法吗? This would be especially useful when starting to decommission an old front-end but still using the backend.
当开始停用旧的前端但仍在使用后端时,这将特别有用。
Try to use this package from npm to create a Node.js proxy for Express: http-proxy-middleware尝试使用 npm 中的 package 为 Express 创建 Node.js 代理: http-proxy-middleware
Then You can configure the target option to proxy requests to the correct domain:然后您可以配置目标选项以将请求代理到正确的域:
const proxy = require('http-proxy-middleware')
app.use('/api', proxy({ target: 'http://localhost:5000', changeOrigin: true }));
Find similar package for next.js here: next-http-proxy-middleware在此处查找 next.js 的类似 package: next-http-proxy-middleware
Another way is to use rewrites config: https://nextjs.org/docs/api-reference/next.config.js/rewrites另一种方法是使用重写配置: 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*'
},
]
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.