2017-02-04 52 views
-5

我需要從服務器端連續調用一個API,以便它每秒24/7被調用。我怎樣才能做到這一點?如何在Node js/Express js中從服務器端連續調用API本身?

我嘗試它在server.js中顯示如下,但得到'TypeError:request.put不是一個函數'。

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); 
}); 
+0

[調用函數每60秒](http://stackoverflow.com/questions/3138756/calling-a-function-every-60-seconds) –

回答

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. 
    } 
}) 
+0

得到的可能的複製'TypeError:request.put不是函數'。 –

+0

@ G.Mounika - 我不能完全幫助你看看我看不到的代碼。您是否使用NPM正確安裝了請求庫? 'request.put()'工作得很好,如果你正確地做事情,顯然你的代碼(我看不到)有一個錯誤。 – jfriend00

+0

我編輯了這個問題。請一次看看它。 –

相關問題