Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  41] [ 4]  / answers: 1 / hits: 21951  / 8 Years ago, sat, june 25, 2016, 12:00:00

I need to call 3rd party api from backend in NodeJS and return the data to ajax call in frontend



Below is my code:



router.post('/get_data', function(request, response){
var city_name = request.body.city_name;
if(city_name in city_name_done){

}
else {
city_name_done.push(city_name);
console.log('city_name: ' + city_name);
var options = {
host : 'api.openweathermap.org',
path : '/data/2.5/forecast/daily?q=' + city_name + '&mode=json&units=metric&cnt=14&appid=75e843de569fb57a783c2e73fd9a7bb5',
method : 'GET'
}
var maybe = '';
console.log('till here')
var req = http.request(options, function(res){
var body = ;
res.on('data', function(data) {
console.log('data came');
body += data;
});
res.on('end', function() {
console.log('ended too');
maybe = JSON.parse(body);
console.log(maybe.city);
});
});
console.log('here too man');
req.on('error', function(e) {
console.log('Problem with request: ' + e.message);
});
response.send(maybe);
}
});


I am able to get the city_name parameter from ajax post request from frontend side however I get 500 internal server error everytime I execute the post request



PS: Pardon my English and even the level of the question as I am an absolute beginner in NodeJS


More From » ajax

 Answers
7

You are returning response from outside of function call that gets data from 3rd party api. You need to return response from res.on('end' section. It is because api call is asynchronous and we have to wait for response to come.


res.on('end', function() {
console.log('ended too');
maybe = JSON.parse(body);
console.log(maybe.city);
response.send(maybe);
});

Complete code is


    router.post('/get_data', function(request, response){
var city_name = request.body.city_name;
if(city_name in city_name_done){

}
else {
city_name_done.push(city_name);
console.log('city_name: ' + city_name);
var options = {
host : 'api.openweathermap.org',
path : '/data/2.5/forecast/daily?q=' + city_name + '&mode=json&units=metric&cnt=14&appid=75e843de569fb57a783c2e73fd9a7bb5',
method : 'GET'
}
var maybe = '';
console.log('till here')
var req = http.request(options, function(res){
var body = "";
res.on('data', function(data) {
console.log('data came');
body += data;
});
res.on('end', function() {
console.log('ended too');
maybe = JSON.parse(body);
console.log(maybe.city);
response.send(maybe);
});
});
console.log('here too man');
req.on('error', function(e) {
console.log('Problem with request: ' + e.message);
});
res.end();
}
});

[#61637] Thursday, June 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
;