如何用Node的express-http-proxy解决REST路径重复代理问题
解决express-http-proxy路径匹配问题
我来帮你搞定这个代理路径的问题~
你遇到的核心问题是:当你用app.use('/rest', proxy('localhost:2011/'))时,Express会自动把请求路径里的/rest前缀去掉,然后把剩下的部分拼到代理目标的URL后面。比如你访问本地的/rest/speakers,实际会被代理到http://localhost:2011/speakers,但你要的目标接口是http://localhost:2011/rest/speakers,所以才会出现必须访问/rest/rest/speakers才能命中的情况。
要解决这个问题,你可以利用express-http-proxy提供的配置选项来调整路径映射:
方案一:使用pathRewrite重写路径
这个方法最直接,通过重写规则把本地的/rest前缀映射到目标服务器的/rest前缀:
var proxy = require('express-http-proxy'); var app = require('express')(); app.use('/rest', proxy('localhost:2011', { pathRewrite: { '^/rest': '/rest' // 保留/rest前缀,让本地/rest/speakers → 目标/rest/speakers } })); app.listen(8081, function () { console.log('Listening on port 8081'); });
方案二:使用proxyReqPathResolver自定义路径
如果你需要更灵活的路径处理,可以用这个函数手动拼接目标路径:
var proxy = require('express-http-proxy'); var app = require('express')(); app.use('/rest', proxy('localhost:2011', { proxyReqPathResolver: function(req) { // req.url是去掉/rest后的路径(比如/speakers),这里手动加上/rest前缀 return '/rest' + req.url; } })); app.listen(8081, function () { console.log('Listening on port 8081'); });
这样修改后,你访问本地的/rest/speakers就会被正确代理到http://localhost:2011/rest/speakers啦~
内容的提问来源于stack exchange,提问作者Peter Kellner
相关产品推荐
相关产品推荐

