【问题标题】:http-proxy-middleware not proxying to index page of other server?http-proxy-middleware 不代理到其他服务器的索引页面?
【发布时间】:2019-02-16 15:38:49
【问题描述】:

我有两台服务器在 Docker 上运行。一个是localhost:3000 的反应前端,而后端在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

【问题讨论】:

    标签: reactjs http-proxy-middleware


    【解决方案1】:

    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 选项可用于更量身定制的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多