简体   繁体   中英

How to send API response through express

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); }); 

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);
});

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