如何将数据从第一台服务器发送到其他服务器并在Node.js中的第一台服务器中获得其他服务器的响应?

时间:2018-10-29 10:19:03

标签: node.js express

我想在服务器1上进行请求或api调用,然后该服务器自动向服务器2发出请求并将响应发送回服务器1。我正在使用NodeJs和Express。

示例:

app.post('/api/Is', function(req, response, callback) {

})

我在postmain中将该API称为:http://localhost:3000//api/Is

因此它应该自动进行http://localhost:5000//api/Is并将响应发送回http://localhost:3000//api/Is呼叫。 我只应该调用http://localhost:3000//api/Is,在后端代码中它将接收请求正文并将其传递给http://localhost:5000//api/Is,然后将响应发送回http://localhost:3000//api/Is

2 个答案:

答案 0 :(得分:1)

您需要使用任何库来从server1到server2进行API调用。下面的代码我正在使用提取库。

要安装提取库

npm install node-fetch --save

       
       
        //SERVER1//

const fetch = require('node-fetch');

router.get("/api/Is", async (req, res) => {
  try{
    let {success, data} = await getDataFromServer2(req);
    if(success) return res.send({success: true, data: data})
    res.send({success: false})
  }catch(e){
    res.send({success: false})
  }
});

function getDataFromServer2(req){
  return fetch('http://localhost:5000//api/Is', { 
    method: 'post',
    body:    req,
    headers: { 'Content-Type': 'application/json' },
  }).then(res => res.json())
    .then((response)=>{
      return {
       success: true,
       data: response
      }
    }).catch((error) => {
      throw new Error("unable to fetch the roles ")
    })
  }

答案 1 :(得分:1)

我认为您可以考虑使用代理库,例如“ node-http-proxy”,这是最简单的方法。

否则,您必须使用“ http moudle”来传送请求和响应,这样(不进行调试,不确定它是否可以正常工作〜):

const http = require('http');
app.post('/api/Is', function(req, response, callback) {
const options = {
    host:'localhost',
    port:'5000',
    path:'/api/Is',
    method: 'POST'
    // maybe need pass 'headers'?
};

let proxyBody = '';
const req2 = http.request(options, function(res2) {
    res2.on('data',function(chunk){
        proxyBody += chunk;
    }).on('end', function(){
        // here can feedback the result to client, like:
        // const { headers } = res2;
        // response.send(proxyBody)
    });
});
// .on('error'){}  here handle the error response

req2.end();
});