javascript - Receiving API info after it responds to client (sending undefined instead of api info) -


this node.js file, what's happening is, user inputs id , gets sent server-side, server takes , searches through api on third-party. problem having is, response initial id sent user gets res.end before info api, getting big fat undefined or empty string on client side. how can make res.end waits until receives data api , sends client? or going @ entirely wrong , shouldn't doing way?

var http = require('http'); var https = require('https'); var url = require('url');`  http.createserver(function (req, res) {      var id = url.parse(req.url,false).query;      var realid = getinfofromapi(id);      res.setheader('access-control-allow-origin', '*');     res.writehead(200);      res.end(json.stringify(realid));  }).listen(3000, '127.0.0.1');  function getinfofromapi(id) {     var url = "https://random.com/" + id + "?api_key=blabla";      var test = https.get(url, function(res) {         var body = '';          res.on('data', function(chunk) {             body += chunk;         });          res.on('end', function() {             var theid = json.parse(body)             console.log("got response: ", theid);         });     }).on('error', function(e) {           console.log("got error: ", e);     }); return test; } 

any info should looking or resources me appreciated, in advance help.

also bonus question, should using post method instead of server api-server? or post privacy matter client server? i'm curious if clever clients able access server http.requests if use instead of post or if matters @ since it's server , not client.

oh , thing, debating if should use https.createserver since have use https https.get, way remove http module require , use https. there big difference in performance or if that?

thanks again in advance.

edit:

http.createserver(function (req, res) {     var id = url.parse(req.url, false).query;      var link = "https://random.com/" + id + "?api_key=blabla";     var testo = https.get(link, function (rez) {         var body = '';         rez.on('data', function (chunk) {             body += chunk;         });         rez.on('end', function () {             var endres = body             res.setheader('access-control-allow-origin', '*');             res.writehead(200);             res.end(endres);         });     }).on('error', function (e) {         console.log("got error: ", e);     }); }).listen(3000, '127.0.0.1'); 

i managed change after read callbacks. thank that. works fine now, happy, again. question though is, work flawlessly if dozens or hundreds of people searching @ same time? each client connected server own seperate function thing runs @ own pace without interfering others? again help.


Comments