Express JS通配符路由代理

我正在使用express-http-proxy来代理后端服务器。 我想所有的请求/代理/代理/苹果/品牌或/代理/橙子/品牌/ nnnn等被代理到后端服务。

所以,我在这里设置了一个通配符代理。

'use strict'; var express = require('express'); var proxy = require('express-http-proxy'); var app = express(); // "" app.use('/proxy*', proxy('https://backend-server.com/' ,{ forwardPath: function(req, res) { console.log(req.url) return require('url').parse(req.url).path; } })); var port = 3000; app.listen(port, function() { console.log('listening on port ' + port + '.') }); 

我期望这个https:// localhost:3000 / proxy / oranges / brand / nnnn被代理到https://backend-server.com/oranges/brand/nnnn

但我只是得到

不能GET / proxy / aa

我不确定这里有什么问题。 通配符路由看起来相当不错。 这里有什么想法?

你可以尝试request模块。 这个解决scheme完全适合我

 var request = require( 'request' ); app.all( '/proxy/*', function( req, res ){ req.pipe( request({ url: config.backendUrl + req.params[0], qs: req.query, method: req.method }, function( error, response, body ){ if ( error ) console.error( 'Wow, there is error!', error ); })).pipe( res ); }); 

或者,如果你仍然想使用express-http-proxy你需要写

 app.use( '/proxy/*', proxy('https://backend-server.com/', { forwardPath: function( req, res ){ return req.params[0]; } }));