如何在动态路由上设置 http-proxy-middleware?



我正在尝试代理一些资产路由,其中路径的动态部分来自配置文件。我使用request库进行了这项工作,但我无法完全让它与http-proxy-middleware一起工作。

以下是我使用request库时有效的代码

const assets = express.Router();
app.use(`/${p.name}/assets`, assets);
assets.get('*', async (req, res) => {
return request(`${p.address}/${p.version}/assets${req.path}`).pipe(res);
});

我已经尝试了几种不同的http-proxy-middleware变体,但这些都不起作用。示例 1:

app.use(
`/${p.name}/assets`,
httpProxy({
target: `${p.address}`,
changeOrigin: true,
pathRewrite: {
[`^${p.name}`]: `${p.version}`,
},
})
);

示例 2:

app.use(
`/${p.name}/assets`,
httpProxy({
target: `${p.address}`,
changeOrigin: true,
pathRewrite: function(path) {
return path.replace(p.name, p.version);
}
})
);

我还尝试使用/${p.name}/assets/**作为app.use的第一个参数,并且我还尝试在pathRewrite对象的键和值的末尾添加一个/assets。结果总是相同的:我为浏览器请求的资产得到 302。

我什至尝试在记录到控制台的httpProxy调用之前添加一个中间件函数,以便我知道我的请求正在到达正确的路由:

app.use(
`/${p.name}/assets`,
(req, _res, next) => {
console.log("I'm an asset proxy, short and stout: ", req.url);
next();
},
httpProxy({
target: `${p.address}`,
changeOrigin: true,
pathRewrite: {
[`^${p.name}`]: `${p.version}`,
},
})
);

但我从来没有看到过这种输出。可能是一个简单的错误。也许我对app.use的第一个论点是不对的?感谢帮助!

更新

我也尝试了旧方式和新方式的组合。我在/${p.name}/assets上安装了一个新的路由器,在发现onProxyRequest选项后,我在那里添加了一个函数来记录一些输出。

const assets = express.Router();
app.use(`/${p.name}/assets`, assets);
assets.use(
'*',
httpProxy({
target: p.address,
changeOrigin: true,
pathRewrite: {
[`^${p.name}`]: p.version,
},
onProxyReq: (proxyReq, req, res) => {
console.log("Hello I'm being proxied now! ", proxyReq, req, res);
},
})
);

仍然得到 302,我从未看到onProxyReq函数的输出。

文档具有自定义路由器选项。

-

const proxyTable = {
'integration.localhost:3000': 'http://localhost:8001', // host only
'staging.localhost:3000': 'http://localhost:8002', // host only
'localhost:3000/api': 'http://localhost:8003', // host + path
'/rest': 'http://localhost:8004', // path only
};
const options = {
target: 'http://localhost:8000',
router: proxyTable,
};
const myProxy = createProxyMiddleware(options);
function customRouter(req) {
// I dont know what "p" stands for 
// check the req object to see which property you want to modify
console.log(req)
const { hostname } = req
const hostName = hostname.split('.')[0]
return `https://${hostName}.sub.domain.com`
}

然后添加此选项:

router: customRouter

你能检查一下你安装的版本吗 - 看起来你正在使用 v0.x.x。 与 HTTP 代理中间件包的接口。最新版本是 2.X.X 版本,它公开了以下函数

const { createProxyMiddleware } = require('http-proxy-middleware');
app.use(
`/${p.name}/assets`,
createProxyMiddleware({
target: `${p.address}`,
changeOrigin: true,
pathRewrite: {
[`^${p.name}`]: `${p.version}`,
},
})
);

最新更新