在nodejs中發起json post的字元長度問題

在 nodejs 專案中, 若是需要對外發起使用 application/json 的 http post , 若有中文字, 需要注意計算字串長度的問題. 一般發起的程式碼請參考:

http://tech.pro/tutorial/1091/posting-json-data-with-nodejs

不過該範例是使用英文字, 所以沒有問題, 若是要發起中文字的 json http post, 需要調整計算 Content-Length 的方式, 使用 new Buffer(str).length, 如下:

var obj_json = { name: "王大頭", age: 25 };
var json_string = JSON.stringify(obj_json);

var req = http.request({
        host: 'host.example.com',
        port: 80,
        path: '/upload',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': new Buffer(json_string).length
        }
    }, function(res) {
    res.setEncoding('utf-8');
    var responseString = '';
    res.on('data', function(data) {
        responseString += data;
    });
    res.on('end', function() {        
        console.log(responseString);
    });
});

req.on('error', function(e) {
  // http post error
});    

req.write(json_string);
req.end();

參考資料: http://cnodejs.org/topic/50616f5301d0b801482695cf