如何使用节点http-proxy代理到根路径

Mic*_*ael 4 proxy node.js express node-http-proxy

我正在尝试将Express应用程序的代理设置为应用程序中特定路径的根路径:

http://my-domain.com/some/route --> http://another-domain:8000/
Run Code Online (Sandbox Code Playgroud)

我已经根据http-proxy文档尝试了多种方法,但是我一直在用路径/路由碰壁。我正在尝试在已登录的Express应用程序中执行此操作,以便我也可以在尝试代理的应用程序后面使用身份验证。我不断收到与代理的应用程序有关的错误,说未定义路径“ / some / route” ...等等。

var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});

proxy.proxyRequest(req, res, {
    host:'localhost',
    port:8000
});
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

var url = 'http://localhost:8000/';
var httpProxy = require('http-proxy'),
    proxy = httpProxy.createProxyServer({});

proxy.web(req,res, { target: url }, function(e) {
    console.log('proxy.web callback');
    console.log(e);
});
Run Code Online (Sandbox Code Playgroud)

该函数调用,但我最终遇到一个明确的404错误...

如果可能的话,我也想传递一些变量,例如:

http://my-domain.com/some/route?var1=something&var2=something --> http://another-domain:8000/?var1=something&var2=something
Run Code Online (Sandbox Code Playgroud)

但是无法弄清楚这是否可行,我尝试在请求上进行设置,因为该请求已发送到proxyRequest中,但无法在第二个应用程序中找到它们。

mik*_*1aj 6

不,您不能只用来做到这一点node-http-proxy

但是有可能http-proxy-middleware(并且您可能已经使用过):

来自@chimurai在github上的评论

您可以使用pathRewrite选项重写路径。

var options = {
  target: 'http://test.com',
  changeOrigin: true,
  pathRewrite: {'^/api' : ''}      // <-- this will remove the /api prefix
};

server.middleware = proxyMiddleware('/api', options);
Run Code Online (Sandbox Code Playgroud)

而且,如果您因使用来这里webpack-dev-server,请注意,它也在内部使用http-proxy-middleware,从版本开始2.0.0-beta请参阅PR)。

旁注:还有一个node-proxy插件http-proxy-rules,因此,如果您不需要中间件,可以使用此插件。


小智 2

好吧,我遇到了另一个问题,但需要先解决这个问题。我想出了这段代码,它对我来说效果很好;)

只需将其用于“/some/route”

.... // your stuff

httpProxy.on('error', function (err, req, res) {
    res.writeHead(500, {
        'Content-Type': 'text/plain'
    });
    res.end('some error');
});

app.all( '/some/route/*' , function( req , res ) {

        var url = req.url;
        url = url.slice(11); // to remove "/some/route"

        req.url = url;

        return httpProxy.web(req, res , { target: "http://another-domain:8000" } );

} );
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。