0

Im currently trying to pass the JSON result from my newsapi.org call. I cannot however figure out how to do it? Any help would be great!! Thanks

newsapi.v2.topHeadlines({
  category: 'general',
  language: 'en',
  country: 'au'
}).then(response => {
  //console.log(response);
  const respo = response;
});

app.get('/', function (req, res){
    res.send(respo);
});

2
  • what is the error you are receiving? did you start your node server? what port is it running on? what happens when you type localhost:<port number> into your browser? Commented Jul 14, 2019 at 5:49
  • What are you getting when you are visiting at the index route: /. You must be getting an error that TypeError: respo is not defined. that newsapi call must be inside the app.get("/") call as this is asynchronous. Your question is incomplete, make sure you provide us a minimum reproducible example stackoverflow.com/help/minimal-reproducible-example Commented Jul 14, 2019 at 5:49

1 Answer 1

2

If you wish to call the API in each new request, then you would put it inside the request handler:

app.get('/', function (req, res){
    newsapi.v2.topHeadlines({
      category: 'general',
      language: 'en',
      country: 'au'
    }).then(response => {
      //console.log(response);
      res.send(response);
    }).catch(err => {
      res.sendStatus(500);
    });
});

If you wish to call the API every once in awhile and cache the result, then you would do something like this:

let headline = "Headlines not yet retrieved";

function updateHeadline() {

    newsapi.v2.topHeadlines({
      category: 'general',
      language: 'en',
      country: 'au'
    }).then(response => {
      headline = response;
    }).catch(err => {
      headline = "Error retrieving headlines."
      // need to do something else here on server startup
    });
}
// get initial headline
updateHeadline();

// update the cached headline every 10 minutes
setInterval(updateHeadline, 1000 * 60 * 10);



app.get('/', function (req, res){
    res.send(headline);
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.