简体   繁体   中英

NodeJS/ExpressJS - Send response of http request back to client

I created a website using Angular 2 and I am using node.js as backend.

I managed to send a request from the angular client to the node.js server and forwarded this from node.js to another application via an HTTP request. My goal is now to send the response from the third application back to the angular client page (I managed also to get the response from the third application), but I am a newbie in node js/express and I couldn't manage to get the response body out of the HTTP request and send it back to the angular client.

In the nodejs server I have following code (mostly by looking into tutorials):

app.route('/api/test').post((req, res) => {
   postCode(JSON.stringify(req.body));
   //Here I want to send back the response from the third application
   //to the Angular client (instead of 'Hi')
   res.status(200).send('Hi');
});

function postCode(post_data) {

const post_options = {
   host: '127.0.0.1',
   port: '8080',
   path: '/test',
   method: 'POST',
   headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(post_data)
   }
};

// Set up the request
const post_req = http.request(post_options, function (res) {
   res.setEncoding('utf8');
   let responseString = ''
   res.on('data', function (data) {
      responseString += data;
      console.log('Response data: ' + responseString);
   });
   res.on("end", function (data) {
      responseString += data;
      console.log('Response end: ' + responseString);
   });
});

// post the data
post_req.write(post_data);
post_req.end();
}

So, how can I manage now to "use" the response of the HTTP request and send it back in the app.route('/api/arq')?post method to the angular client (Please see also first comment in code)?

Thank you very much and

Kind regards, Yasemin

EDIT: seems like this similar pattern was answered already - External API Calls With Express, Node.JS and Require Module thanks to @madflow for finding it.

First of all you're doing some extra work in my opinion, why not use a framework like express.js?

Anyhow - what I would do is send the request to your third party from within the /api/arq endpoint, call the http.request after receiving a request inside the route and inside res.on("end"... pass the answer along.

 console.log('Response end: ' + responseString);

The above line is the point where you have the data you want to send in your response.

So send the response there , and not immediately after you call postCode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM