Node.js POST导致[Error:socket挂断]代码:'ECONNRESET' [英] Node.js POST causes [Error: socket hang up] code: 'ECONNRESET'
问题描述
我创建了一个示例来将数据发布到休息服务,我发现当我有非ASCII或非拉丁字符(请参阅data.firstName)时,我使用TEST-REST.js的发布请求将抛出
I created a sample to post data to a rest services and I found out that when I have non-ascii or non-latin character (please see data.firstName), my post request using TEST-REST.js will throw
错误:{[错误:插座挂断]代码:'ECONNRESET'}。
error: { [Error: socket hang up] code: 'ECONNRESET' }.
// TEST-REST.js
var http = require('http');
var data = JSON.stringify({
firstName: 'JoaquÌn',
});
var options = {
host: '127.0.0.1',
port: 3000,
path: '/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
var req = http.request(options, function(res) {
var result = '';
res.on('data', function(chunk) {
result += chunk;
});
res.on('end', function() {
console.log(result);
});
});
req.on('error', function(err) {
console.log(err);
});
req.write(data);
req.end();
在我的休息服务中,它会像我这样发错:
and on my rest services, it throw me error like this:
SyntaxError: Unexpected end of input Sun Sep 08 2013 23:25:02 GMT-0700 (PDT) - at Object.parse (native)
at IncomingMessage.<anonymous> (/Volumes/Data/Program_Data/GitHub/app/node_modules/express/node_modules/connect/lib/middleware/json.js:66:27) info at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:920:16 : - - - [Mon, 09 Sep 2013 06:25:02 GMT] "POST /users HTTP/1.1" 400 - "-" "-"
at process._tickDomainCallback (node.js:459:13)
如果我将firstName值从JoaquÌn替换为 abc',一切都很好。我想我缺少一些支持或逃脱使其工作。
if I replace firstName value from 'JoaquÌn' to 'abc', everything works just fine. I think I'm missing something to support or escape to make it work.
有没有人有任何想法我如何解决这个问题?我也尝试过:require('querystring')。escape(model.givenName),它的作品,但我不满意。
does anyone have any idea how I solve this problem? I also tried following: require('querystring').escape(model.givenName), and it works but I'm not happy with it.
UPDATED
我发现如果我注释掉:app.use(express.bodyParser());则该错误消失。
UPDATED I found out that if I comment out: app.use(express.bodyParser());, the error disappears.
推荐答案
这是节点的问题,而不是表达的问题。 https://github.com/visionmedia/express/issues/1749
This is node's issue, not express's issue. https://github.com/visionmedia/express/issues/1749
解决,从
'Content-Length':data.length
'Content-Length': data.length
to
'Content-Length':Buffer.byteLength(data)
'Content-Length': Buffer.byteLength(data)
THUMB规则
始终使用如果您想查找字符串的内容长度,请将 Buffer.byteLength()
更新
我们还应该在服务器端优雅地处理错误,以防止通过添加中间件来处理它的崩溃。
We also should handle error gracefully on server side to prevent crashing by adding middleware to handle it.
app.use(function (error, req, res, next) {
if (!error) {
next();
} else {
console.error(error.stack);
res.send(500);
}
});
这篇关于Node.js POST导致[Error:socket挂断]代码:'ECONNRESET'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!