我有三个快速服务器app1
,app2
和app3
在不同的端口上运行。所有服务器都有路由/api/example
,但只有app1
连接到UI,我想每当我从前端击中app1中的路由/api/example
时,将请求转发到app2
和中的相同路由app3
从app1
中的路由中返回,一旦从其他两个路由返回数据,将它们合并到app1
中并将它们发送回UI。我怎样才能做到这一点呢?
您可以向其他两个服务器发出请求,等待结果从这两个服务器返回,然后将这两个结果处理为您的最终结果:
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()
以匹配您返回的数据类型。