首页 > 解决方案 > 如何通过 express 发送 API 响应

问题描述

我目前正在尝试从我的 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);
});

标签: javascriptnode.jsexpresslocalhost

解决方案


如果您希望在每个新请求中调用 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);
});

推荐阅读