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);
});
localhost:<port number>into your browser?index route: /. You must be getting an error thatTypeError: respo is not defined. that newsapi call must be inside theapp.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