【问题标题】:Accessing routes on different server from within a server (Express)从服务器内部访问不同服务器上的路由(Express)
【发布时间】:2021-02-26 20:01:38
【问题描述】:

我有三台快速服务器 app1app2app3 在不同的端口上运行。所有服务器都有一个路由/api/example,但只有app1 连接到UI,每当我从前端点击app1 中的路由/api/example 时,我希望将请求转发到app2 中的同一路由和 app3 来自app1 中的路由,并且一旦从其他两个路由返回数据,将它们组合在app1 中并将它们发送回UI。我怎样才能做到这一点?

【问题讨论】:

    标签: node.js express


    【解决方案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() 以匹配您返回的数据类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-27
      • 2019-02-02
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 2015-12-07
      相关资源
      最近更新 更多