krishan singh
krishan singh

Reputation: 1

How to send data from first server to other and get other server response in first server in nodejs?

I want to make a request or api call on server 1, this server then automatically request to Server 2 and send the response back to server 1. I am using NodeJs and Express.

Example:

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

})

I am calling that API in postmain as : http://localhost:3000//api/Is

So it should automatically go on http://localhost:5000//api/Is and send the response back to http://localhost:3000//api/Is call. I should only call http://localhost:3000//api/Is and in backend code it will take request body and pass it to http://localhost:5000//api/Is and send the response back to http://localhost:3000//api/Is

Upvotes: 0

Views: 1431

Answers (2)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

you need to use any library to make API call from server1 to server2. below code I am using fetch library.

To install the fetch library

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 ")
    })
  }

Upvotes: 1

oyster
oyster

Reputation: 111

I think you can consider use the the proxy lib like 'node-http-proxy', the most easy way.

otherwise, you must be transfer the request and response use 'http moudle', like this(no debug, not sure it will work perfectly~):

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();
});

Upvotes: 1

Related Questions