[英]How to send API response through express
Im currently trying to pass the JSON result from my newsapi.org call. 我目前正在尝试通过newsapi.org调用传递JSON结果。 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: 如果希望在每个新请求中调用API,则可以将其放入请求处理程序中:
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: 如果您希望每隔一段时间调用一次API并缓存结果,则可以执行以下操作:
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.