我有两个在Docker上运行的服务器。一个是在localhost:3000
的React前端,而在localhost:9000
的后端运行。当我转到localhost:3000 / api时,我想转到后端的索引页,即localhost:9000
。
在通过create-react-app创建的myApp文件夹中创建了setupProxy.js文件:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api', { target: 'http://backend:9000' }));
};
当我去localhost:3000/api
时,我被发送到localhost:9000/api
而不是localhost:9000
。
答案 0 :(得分:2)
http-proxy-middleware
有一个pathRewrite
选项,请参见documentation。
在您的特定情况下:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api', {
target: 'http://backend:9000',
pathRewrite: {'^/api' : ''}
}));
};
这通常应该将localhost:3000/api/endpoint
重写为localhost:9000/endpoint
。
请注意,还有一个router
选项可用于更个性化的行为。