我试图让http-proxy-middleware正常工作,我想要实现的是运行多个nodejs应用程序,然后将代理应用程序作为反向代理服务器。
我遇到的问题是当我按下代理应用程序上的链接时,这是我的代码:
var express = require('express')
var proxy = require('http-proxy-middleware')
var app = express()
var options = {
target: 'http://localhost:1001', // target host
changeOrigin: true, // needed for virtual hosted sites
ws: false, // proxy websockets
logLevel: "debug",
pathRewrite: {
'^/foo': '/', // rewrite path
}
}
var exampleProxy = proxy(options)
app.use('/foo', exampleProxy)
app.listen(3000)
在localhost:1001 app我得到了路线'/'和'/ bar'
app.get('/', function (req, res) {
res.render('home');
});
app.get('/bar', function (req, res) {
res.render('bar');
});
如果我去localhost:3000 / foo它会将我重新路由到localhost:1001 /(同时在浏览器中显示localhost:3000 /)和localhost:3000 / foo / bar相同。所以这很好。
当我转到localhost:3000 / foo然后按下“bar”链接时会出现问题,它会将我路由到localhost:3000 / bar,这不是我在代理服务器中定义的路由。
所以我需要的是,当我按下链接到/ bar时,它会将它路由到代理中的/ foo / bar。
我已经尝试了一些方法来解决这个问题,但(显然)没有成功:
将端口(1001)添加到响应(res.locals.portNo =“1001”),然后在请求中发送它,以便代理可以检查请求的来源并添加/ foo(如果是1001)。 (我还没有尝试过,但也许这可以通过使用cookies来实现?)
我得到了它的工作,但这是一个非常糟糕的黑客......但它的工作原理......
我添加了cookie-parser
var cookieParser = require('cookie-parser')
app.use(cookieParser())
然后我添加了这个丑陋的中间件
app.use(function (req, res, next) {
var domainLetter = req.cookies.domainLetter
switch (req.url.substring(0, 2)) {
case "/a": {
domainLetter = 'a'
res.cookie('domainLetter', 'a')
break
}
case "/b": {
domainLetter = 'b'
res.cookie('domainLetter', 'b')
break
}
default: {
break
}
}
if (req.url.length != 2 || req.url.substring(0, 2) != '/' + domainLetter)
req.url = '/' + domainLetter + req.url
next()
})
所以我正在做的是当我想使用localhost的代理时:1001,我转到localhost:3000 / a(或localhost:3000 / a / ****),然后它将保存带有属性的cookie“ domainLetter“的值为”a“,然后每当我点击该网站上的链接时,它会将”/ a“添加到该网址(localhost:3000 / test成为localhost:3000 / a / test等)