简体   繁体   中英

Node JS Request external API and send it back to client side AJAX

So I have a Node.js server that route does one thing. When called by a button click on client side, it goes here and fetches data from external API.

app.get('/ajaxcall', function(req, res) {
const options = {
    url: 'hidden url',
    method: 'POST',
};

request(options, function(err, request, body) {
    if (err) {
        request.send('There was an error with fetching API');
    }
    else {
        console.log(res.statusCode);
        return res.end(JSON.stringify(body));
    }
});
});

Then I have this bit that goes and fetches this data from the server.

$(document).ready(function(){
$('#searchButton').click(function(event){
event.preventDefault()
$.ajax({
  type: 'GET',
  url: '/ajaxcall',
})
.done(function(result){
  let data = jQuery.parseJSON(result);
  console.log(data)
  console.log(data[0].formatted_address)
})
.fail(function(xhr, status, error){
  console.log(error)
})
.always(function(data){})
})
})

The thing is that console.log(data) will output everything into the console, but console.log(data.[0].formatted_address) outputs undefined.

I am trying to grab data from this JSON that I get back, so I can display it on the website. Can anyone tell me why console.log(formatted_address) does not work on client side, but works on server side? Is there a way to loop through this JSON object and pick bits I need?

Here's how the JSON look JSON screenshot

If the JSON you posted is what is deserialized into the data variable on the front-end, it seems like data is a JSON object that contains a results field which is an array instead of the data object itself being an array.

Try something like data.results[0].formatted_address

Here is an example of how to change the .done function to loop though some of the data using the forEach array function.

.done(function(result){
  let data = jQuery.parseJSON(result);

  data.results.forEach(function(result) {
        console.log(result.formatted_address);
        console.log(result.geometry.location.lat, result.geometry.location.lng);
        console.log(result.icon);
    });
})

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