Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  8] [ 5]  / answers: 1 / hits: 34849  / 10 Years ago, mon, november 3, 2014, 12:00:00

I'm using the request module to make an HTTP GET request to an url in order to get a JSON response.



However, my function is not returning the response's body.



Can someone please help me with this?



Here is my code:



router.get('/:id', function(req, res) {
var body= getJson(req.params.id);
res.send(body);
});


Here is my getJson function:



function getJson(myid){
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'http://www.XXXXXX.com/api/get_product.php',
method: 'GET',
headers: headers,
qs: {'id': myid}
}

// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
return body;
}
else
console.log(error);
})
}

More From » json

 Answers
40
res.send(body); 


is being called before your getJson() function returns.



You can either pass a callback to getJson:



getJson(req.params.id, function(data) {
res.json(data);
});


...and in the getjson function:



function getJson(myid, callback){
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'http://www.XXXXXX.com/api/get_product.php',
method: 'GET',
headers: headers,
qs: {'id': myid}
}

// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body);
}
else
console.log(error);
})

}


or simply call:



res.json(getJson(req.params.id));

[#68927] Friday, October 31, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nia

Total Points: 461
Total Questions: 97
Total Answers: 93

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
;