我有三个快速服务器 app1
、app2
和 app3
在不同的端口上运行。所有服务器都有一个路由 /api/example
,但只有 app1
连接到 UI,我希望每当我从前端点击 app1 中的路由 /api/example
时,将请求转发到相同的app2
and app3
中的路由来自 app1
中的路由,一旦数据从其他两条路由返回,将它们组合在 {{ 1}} 并将它们发送回 UI。我怎样才能做到这一点?
答案 0 :(得分:1)
您可以只向其他两个服务器发出请求,等待结果从两者返回,然后将这两个结果处理为最终结果:
const got = require('got');
const port2 = somePort2; // port for app2
const port3 = somePort3; // port for app3
app1.get("/api/:command", (req, res) => {
Promise.all([
got(`http://localhost:${port2}/api/${req.params.command}`).json(),
got(`http://localhost:${port3}/api/${req.params.command}`).json(),
]).then(([r2, r3]) => {
// process r2 and r3 to combine them
res.send(...);
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
});
注意,这里假设您从 app2 和 app3 获取 JSON。如果是不同类型的数据,则调整 .json()
以匹配您返回的数据类型。