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:
Error: socket hang up using node v0.12.0
but no one actually work for my scenario.
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)' ]
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.
for me - solved by add Content-Length header.
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(JSON.stringify(order))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.