【问题标题】:How to call an API continuously from server side itself in Node js/Express js?如何在 Node js/Express js 中从服务器端本身连续调用 API?
【发布时间】:2017-06-21 15:52:35
【问题描述】:

我需要从服务器端本身不断调用 API,以便每秒 24/7 调用它。我怎样才能做到这一点?

我在 server.js 中尝试如下所示,但得到'TypeError:request.put is not a function'。

app.get('/',function(request,response){
    setInterval(function(){
        request.put('http://localhost:4242/changepaidstatus', function(error,response){
            if (error){
                console.log(error);
            }
            else{
                console.log(response);
            }
        });
    }, 1000);
});

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

setInterval() 会让你每秒重复一些功能。

setInterval(() => {
    // will execute every second
}, 1000);

至于调用 API,您可以使用 request() module 发出任何您想要的 http 请求。以下是来自their doc 的示例:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage. 
  }
})

【讨论】:

  • 得到 'TypeError: request.put is not a function'。
  • @G.Mounika - 我无法为您提供我看不到的代码。您是否使用 NPM 正确安装了请求库? request.put() 如果您做的事情正确,就可以正常工作,因此显然您的代码(我看不到)中有错误。
猜你喜欢
  • 2017-11-09
  • 1970-01-01
  • 2020-06-23
  • 2019-02-15
  • 2016-02-26
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 2020-11-20
相关资源
最近更新 更多