Search code examples
node.jsapihttpsquery-stringeconnreset

Why do I get ECONNRESET in the terminal, but not the browser?


I have a very simple nodejs program that I am using to demonstrate communication with the Alchemer API. Whenever I run the following code, there is a few seconds of delay, and then an error is thrown with the identifier ECONNRESET. However, when I copy the same url into the browser or Postman, it works just fine.

Nodejs Snippet

require('dotenv').config();
const https = require('https');
const querystring = require('querystring');

const params = {
    api_token: process.env.API_TOKEN,
    api_token_secret: process.env.API_TOKEN_SECRET
};

const reqArgs = querystring.stringify(params);

console.log('Query string: ', reqArgs);

const reqOptions  = {
    host: 'api.alchemer.com',
    path: '/v5/survey?' + reqArgs
}

console.log('Query: ', reqOptions.host + reqOptions.path);
console.log('Getting data...');
    
const req = https.request(reqOptions, resp => {
    let data = '';

    resp.on('data', chunk => {
        data += chunk;
    });

    resp.on('error', err => {
        console.error('Error on response:');
        console.error(err);
    });

    resp.on('end', () => {
        console.log('Request complete:');
        console.log(data);
    });
});

req.on('error', (err) => {
    console.error('Error on request:');
    console.error(err);
})

Error Observed

Error: socket hang up
    at connResetException (internal/errors.js:607:14)
    at TLSSocket.socketOnEnd (_http_client.js:493:23)
    at TLSSocket.emit (events.js:327:22)
    at endReadableNT (internal/streams/readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: 'ECONNRESET'
}

Solution

  • Because you don't call req.end() ! So it never sends a request to the backend.