5

I followed the node http document to write a delete request to the local server, but receive the socket hang up error, similar question I checked are:

I believe it is the code error because I use postman it works for me, following is my code

var options = {
    hostname: 'localhost',
    port: 3000,
    path: '/accounts/abc'
    method: 'DELETE',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
};

var order = {
    "secret": "abc_secret"
};

var content = JSON.stringify(order);
var req = http.request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    res.on('data', function(chunk) {
        console.log('resp: ' + chunk);
    });
});


req.on('error', function(err) {
    console.error('error: ' , err.stack.split("\n"));
});

req.write(content);

req.end();

and the errors are:

error:  [ 'Error: socket hang up',
  '    at createHangUpError (_http_client.js:215:15)',
  '    at TLSSocket.socketOnEnd (_http_client.js:300:23)',
  '    at TLSSocket.emit (events.js:129:20)',
  '    at _stream_readable.js:908:16',
  '    at process._tickCallback (node.js:355:11)' ]
Community
  • 1
  • 1
Haven
  • 7,808
  • 5
  • 25
  • 37

2 Answers2

6

Apparently, the request header does not have content length. Therefore, whatever you wrote in the write function will be ignored. Hope this is the root cause.

biajee
  • 565
  • 1
  • 4
  • 20
0

for me - solved by add Content-Length header.

 headers: {
    'Content-Type': 'application/json; charset=utf-8',
    'Content-Length': Buffer.byteLength(JSON.stringify(order))
 }
Git
  • 41
  • 6