node.js https request error event issue

1.7k Views Asked by At

I'm using node.js (10.23) https lib to send request to a 3rd party web service. Everything appears ok, but recently I found a weird issue which has confused me.

Here is the code:

var https = require('https');        

function callWebService(requestOpts,body,accessToken,callback){
    var options = {
        host: requestOpts.host, 
        path: requestOpts.path,
        method: 'POST',
        headers: {
            'Content-Type':'application/json',
            'Content-Length': Buffer.byteLength(body),  
            'Authorization':'Bearer '+accessToken
        }
    };

    var req = https.request(options, function(res) {
        logger.log('STATUS: ' + res.statusCode);
        logger.log('HEADERS: ' + JSON.stringify(res.headers));

        if(res.statusCode!='200') {
            var error = new Error("Web service call failed");
            return callback(error);           
        } else {
            logger.log('web service call success');
            return callback();
        }   
    });

    req.on('error', function(e) {
        logger.error('call web service,error occurs: ' + e.message);
        return callback(e);     
    });
    req.write(body);
    req.end();
}

Sometimes (not every time) I can see both success and errors in the logs, the error is 'read ECONNRESET'. I don't really know why this occurs.

From my view, a http(s) transaction is one request and one response, how could it be one request, but get possible two responses.

And I checked node.js official document, it says

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object.

So I guess that maybe the http(s) request and response work fine and the error happens on 'TCP level', but why is the call back is called twice?

0

There are 0 best solutions below