首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过快递发送API响应

如何通过快递发送API响应
EN

Stack Overflow用户
提问于 2019-07-14 05:43:15
回答 1查看 136关注 0票数 0

我目前正在尝试从我的newsapi.org调用中传递JSON结果。但我想不出该怎么做?任何帮助都会很好!!谢谢

代码语言:javascript
复制
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);
});

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-14 05:49:54

如果希望在每个新请求中调用API,则将其放入请求处理程序中:

代码语言:javascript
复制
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并缓存结果,那么您将执行如下操作:

代码语言:javascript
复制
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);
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57024900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档