Webpack开发服务器代理路由器选项不起作用

问题描述

我正在使用Vue CLI设置应用程序。我来配置webpack-dev-server的代理以将请求代理到某个终结点。代理到哪个端点取决于某些请求参数。

根据http-proxy文档,我应该能够使用router选项(而不是target属性,但是target属性webpack-dev-server)。这是我的代理配置的最低版本:

{
  devServer: {
    port: 8080,host: 'localhost',proxy: {
      '/api': {
        target: 'http://localhost:8000',router: function (req) {
          console.log('Proxy router',req.hostname);
          return 'http://localhost:7000';
        },},}
}

我希望在这里发生的事情是,对http://localhost:8080/api的任何请求都将被代理到http://localhost:7000。实际发生的是,它尝试将请求代理到target选项中配置的端点。

为了说明这一点,这是控制台输出

代理路由器本地主机

代理错误:无法将请求/ api / test从localhost:8080代理到http:// localhost:8000 /。

有关更多信息,请参见https://nodejs.org/api/errors.html#errors_common_system_errors(ECONNREFUSED)。

它执行路由器功能(如上面的控制台日志输出所示),但是它似乎只是忽略了结果,而是将其代理到目标端点。根据{{​​1}}文档,使用http-proxy选项时不需要target选项,因此,如果可以的话,我会删除它,但是router本身需要webpack-dev-server选项可以设置并成为有效的URI。

如何在target获取代理以使用路由器功能

解决方法

这似乎是基础http-proxy-middleware的问题。尽管该配置成功完成了将请求从/api代理到http://localhost:7000的操作,但是如果代理请求失败则记录了原始target

const target = (this.proxyOptions.target as any).host || this.proxyOptions.target;
const errorMessage =
  '[HPM] Error occurred while trying to proxy request %s from %s to %s (%s) (%s)';

Source

如果您打开日志级别,则可以看到它正在使用所需的目标:

'/api': {
  target: 'http://localhost:8000',router: function () {
    return 'http://localhost:7000';
  },logLevel: 'debug',},
[HPM] Router new target: http://localhost:8000 -> "http://localhost:7000"
[HPM] GET /api => http://localhost:7000
[HPM] Error occurred while trying to proxy request /api from localhost:8080 to http://localhost:8000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

似乎有人拥有tried to fix this,但PR从未合并,现在有冲突。