我目前正在尝试从我的newsapi.org调用中传递JSON结果。但我想不出该怎么做?任何帮助都会很好!!谢谢
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);
});
发布于 2019-07-14 05:49:54
如果希望在每个新请求中调用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);
});
});如果您希望每隔一段时间调用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);
});https://stackoverflow.com/questions/57024900
复制相似问题