代码之家  ›  专栏  ›  技术社区  ›  Leff

Webpack多个代理不工作-获取404错误

  •  1
  • Leff  · 技术社区  · 6 年前

    我正试图在我的项目中设置多个代理。我在当地有两个项目。在其中一个项目中,我需要从这两个项目的两个远程后端获取数据。我已按如下方式设置Webpack文件:

    var options = {
      contentBase: "src/client",
      proxy: {
        "fpHandling/api/**": {
          target: "http://localhost:8030",
          secure: false,
        },
        "fpCase/api/**": {
            target: "http://localhost:8080",
            secure: false,
        },
      },
      publicPath: config.output.publicPath,
      hot: true,
      noInfo: true,
      historyApiFallback: false,
      stats: {
        colors: true,
      },
    };
    
    var wds = new WebpackDevServer(webpack(config), options);
    
    wds.listen(9999, 'localhost', function(err) {
      if (err) {
          return console.log(err); //NOSONAR
      }
    
      console.log('Listening at http://localhost:9999/');
    });
    

    但是,我无法从远程后端获取数据 fpCase/api/ 我得到 404 错误。但是,同一个端点在另一个项目中工作,我只有一个这样设置的代理:

    proxy: {
        "**/api/**": {
          target: "http://localhost:8080",
          secure: false,
        },
      },
    var wds = new WebpackDevServer(webpack(config), options);
    
    wds.listen(9000, 'localhost', function(err) {
      if (err) {
          return console.log(err); 
      }
    
      console.log('Listening at http://localhost:9000/');
    });
    

    在控制台中,我可以看到请求被发送到

    Request URL: http://localhost:9999/fpCase/api/
    

    我想问题出在端口上,因为运行项目的服务器的端口是 9999 目标的端口是 8080 . 在可以到达此端点的其他项目中,端口设置为 9000 在那里它起作用了。 我做错了什么?我应该如何设置多个代理,以便从两个后端获取数据?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Dacre Denny    6 年前

    如果我正确理解您的问题,那么解决方案应该是使用 pathRewrite 基于每个代理的参数。

    例如,如果你的应用程序在 /fpHandling/api/* 那你就要把请求转送到相当于 http://localhost:9999/* .

    要实现这一点,您可以像这样更新选项配置:

    var options = {
      contentBase: "src/client",
       proxy: {
    
           "/fpHandling/api/*": {
               target: "http://localhost:9999",
               secure: false,
               pathRewrite: { '^/fpHandling/api': '' }
           },
    
           "/fpHandling/spark/*": {
               target: "http://localhost:9999",
               secure: false,
               pathRewrite: { '^/fpHandling/spark': '' }
            },
    
            "/fpCase/api/*": {
               target: "http://localhost:8888",
               secure: false,
               pathRewrite: { '^/fpCase/api': '' }
            }
      },
      publicPath: config.output.publicPath,
      hot: true,
      noInfo: true,
      historyApiFallback: false,
      stats: {
        colors: true,
      },
    };
    

    希望这有帮助!