首页 > 解决方案 > Express 服务器代理多个应用程序

问题描述

我正在尝试为多个节点应用程序编写反向代理。什么时候做这样的事情:

app.use('/', proxy('http://localhost:5010/'));
app.listen(8000, (err) => {
if (err) {
    return console.error('Application failed to start:', err);
}
    console.log('Application listening on port', 8000);
});

它按预期工作。但是当我做类似的事情时

app.use('/', proxy('http://localhost:5010/'));
app.use('/config', proxy('http://localhost:5020/config'));
app.listen(8000, (err) => {
if (err) {
    return console.error('Application failed to start:', err);
}
    console.log('Application listening on port', 8000);
});

我对http://localhost:8000/config的请求被路由到 localhost:5010

如果我只做代理,/config它将正确路由。它是关于我何时做多个代理的。

我为此使用 express 和 express-http-proxy。

关于如何做到这一点的任何想法?

标签: node.jsexpressproxyreverse-proxy

解决方案


Express 中间件按顺序执行。所以你的第一行

app.use('/', proxy('http://localhost:5010/'));

对于/and/config和所有的路线都是如此。因此,如果您想为某些路线做一些不同的事情,请将其放在顶部

app.use('/config', proxy('http://localhost:5020/config'));
app.use('/', proxy('http://localhost:5010/'));

因此,现在您的第一行将仅对/config路径有效,所有其他路由器将前进到 secod 处理程序。


推荐阅读