Nodejs HTTP请求失败并带有一些字符

时间:2015-06-26 10:36:30

标签: node.js http request

我正在使用HTTP请求保存我的数据,并且它正常工作。这是我的代码:

var data = {
    title: request.body.title,
    description: request.body.description
};

var dataString = JSON.stringify(data);
logger.debug(dataString);

var options = {
    hostname: config.hostName,
    port: config.defaultPort,
    path: '/api/save',
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': dataString.length,
        'authToken': token
    }
};

var req = http.request(options, function (res) {
    var dataStr = '';

    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        dataStr += chunk;
    });
    res.on('end', function () {
        var res_data = JSON.parse(dataStr);
        if (res_data.status === "success") {
            response.note = JSON.parse(dataStr);
            callback(null, response);
        } else if(res_data.status === "failure") {
            callback(res_data.message, response);
        }
    });
});
req.write(dataString);
req.end();
req.on('error', function (e) {
    logger.error('problem with request: ' + e.message);
    //callback('problem with request: ' + e.message, null, null);
});

但是,如果任何titledescription字符给我错误socket hang up并且请求失败。为什么字符导致问题。

工作解决方案:我在发送请求之前使用encodeURIComponent(),在收到请求数据后使用decodeURIComponent(),然后它正在工作。在我发送和接收请求数据的每个地方,此解决方案都存在问题,我必须encodedecode

这种情况有没有更好的解决方案?

0 个答案:

没有答案