http-proxy-middleware 中的动态端口 route/path-rewrite

Dynamic Port in http-proxy-middleware route/path-rewrite

是否可以使用 http-proxy-middleware 执行以下操作route/path-rewrite?

'/sec/port/xxx/yyy' => 目标:'https://someotherSite.com:port/xxx/yyy'

根据初始地址,端口是动态的,即

/sec/1234/xxx/yyy => https://someotherSite.com:1234/xxx/yyy

我正在使用快速服务器。

您需要重写路径以便删除 /api/PORT,这可以在 pathRewrite 函数中完成。 newPort 是从req的原始url split.

的第二个索引中得到的端口值

路由器从请求参数中获取需要的端口号,简单拼接为return值,动态改变目标为localhost:PORTNUM。

希望对您有所帮助。

proxyTable: {
'/api': {
    target: 'http://localhost',
    changeOrigin: true,
    pathRewrite:
        function(path,req) {
            //Get the port number
            var newPort = req.originalUrl.split('/')[2];
            //Return the path with the api and portname removed
            return path.replace('/api/'+newPort,'');
        },
    router: function(req) {
        var newPort = req.originalUrl.split('/')[2];
        //Dynamically update the port number to the target in router
        return 'http://localhost:'+newPort;
    }
}