【问题标题】:How to send API response through express如何通过 express 发送 API 响应
【发布时间】:2019-07-14 05:43:15
【问题描述】:

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

【问题讨论】:

  • 您收到的错误是什么?你启动你的节点服务器了吗?它在哪个端口上运行?在浏览器中输入localhost:<port number> 会发生什么?
  • 当您访问index route: / 时会得到什么。您一定会收到TypeError: respo is not defined 的错误。该 newsapi 调用必须在 app.get("/") 调用内,因为这是异步的。您的问题不完整,请确保您向我们提供了一个最小可重复的示例stackoverflow.com/help/minimal-reproducible-example

标签: javascript node.js express localhost


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 2019-12-04
    • 2019-09-03
    • 1970-01-01
    相关资源
    最近更新 更多