While fault发出另一个http请求



我正在尝试创建一个函数,该函数使用nodeJS和express,request返回REST API响应。这是我的代码片段:

var express = require('express')
var httpRequest = require('request');
var bodyParser = require('body-parser');
var app = express() 
// callback -> the function you will call later
function getData1(callback) {
request('http://www.my-server.com/data', function (error, response, body) {
if (!error && response.statusCode == 200) {
// call the function when the function finishes and also passed the `body`
return callback(body);
}
})
} 

app.get('/get-data', function (request, response) {
getData1(function(data1) {
//do something with data
response.send(data1);
})
});
...

这很管用。如果第一个请求有错,我需要再提出一个请求。有一件事就像一个循环===>当请求故障时,再发出一个请求,例如3次,然后如果第三次故障再次返回错误。

你有爱达荷州吗?

向致以最良好的问候

看看这个:

  1. 我设置了一个简单的计数器来计算我进行HTTP调用的次数
  2. 我监视这个计数器,如果它超过3,我执行我想要的任何逻辑
  3. 每次HTTP调用失败时,我都会递增计数器
  4. 每次HTTP失败时,我都会调用自己,在参数中传递递增的计数器
  5. 我在您的路由器中用1作为counter调用您的getData1函数。(app.get)

    function getData1( callback , counter ) { if(counter >= 3){ // Do Something , you have tried the HTTP 3 times already
    }else{ request('http://www.my-server.com/data', function (error, response, body) { if (!error && response.statusCode == 200) callback(body); else{ // Increment the counter counter++; // Now call yourself with the new counter value getData1( callback , counter ); } } }) }

    app.get('/get-data', function (request, response) { getData1(function(data1) { //do something with data response.send(data1); } , 1 ) });

最新更新