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)' ]

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yes, both DELETE and POST method need the content length to be set
0

for me - solved by add Content-Length header.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.