http-proxy-middleware无法代理到其他服务器的索引页吗?

时间:2019-02-16 15:38:49

标签: reactjs http-proxy-middleware

我有两个在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

1 个答案:

答案 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选项可用于更个性化的行为。