Reputation: 75
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);
});
Upvotes: 0
Views: 178
Reputation: 707328
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);
});
Upvotes: 2