Treatment Nodejs http request delay (to prevent crashes)

 

 

Sometimes because the interface is not open, or for other reasons, resulting in http.request request a delay, has been a drain on resources not say, but also cause the program to crash error, delay processing is actually a error handling.

var APIGET = function (URL, the callback) { 
    Debug ( "request to the API service data ..." ); 
    Debug ( "URL:" + URL)
 // The following is the delay time of the transmission request process, generally less than 
    var requestTimer = the setTimeout ( function () { 
        req.abort (); 
        Debug ( 'the Timeout ...... ...... the Request' ); 
    }, 5000 );
     var OP = { 
        Host: CONFIG.API_SERVICE_HOST, 
        Port: CONFIG.API_SERVICE_PORT, 
        Method: 'the GET' , 
        path: URL 
    }; 
 
    var REQ =Http.request ( 
        OP, function (RES) { 
            the clearTimeout (requestTimer); 
// The following is a request interface data, when the lack of response, we return to the closed state to wait for the data, because there are five second timer, 
// 5 seconds If you receive a complete internal data, http module will automatically jump to res.on ( 'end', function ( ) {}) 
// because we res.on ( 'end', function ( ) {}) callback function in the clearTimeout (responseTimer), 
// clear the timer, the timer has to worry about it is repeatedly executed after receiving data. 
            var responseTimer = the setTimeout ( function () { 
                res.destroy (); 
                Debug ( '.. the Timeout the Response ...... .... ' ); 
            }, 5000 );
             var recvData = "" ; 
            res.on ('data', function(chunk) {
                recvData += chunk;
                // debug(recvData);
            });
            res.on('end', function() {
                clearTimeout(responseTimer);
                if (callback) {
                    callback(null, JSON.parse(recvData));
                }
                debug("请求结束");
            });
        });
    req.on('error', function (e) {
        if (callback) {
            callback(e, null);
        }
    });
 
    req.end();
};

 

Address reprint: https://www.cnblogs.com/yourstars/p/6009368.html

Guess you like

Origin www.cnblogs.com/zyulike/p/11495934.html