2

我编写了一个简单的 node.js 程序来演示我在其他地方遇到的问题。

给定以下 node.js 程序:

var http = require('http');
http.createServer(function (req, res) {
// simple repro for json deserializaiton error cause by right quote character '’'
var json = { 'foo': 'bar’s answer' };
var write = JSON.stringify(json);
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': write.length });
res.end(write);
}).listen(8085, '127.0.0.1');

当我使用 chrome 的 Advanced Rest Client 对此进行 POST 时,我得到了 200 OK 响应,但是在响应内容的 JSON 选项卡中,出现了术语“输入意外结束”而不是解析的 json。

在原始选项卡中,显示了字符串“{“foo”:“bar's answer”,这表明无法解析 json 的原因(它缺少结束的 '}')。

如果我从原始对象中删除“”,则响应在返回时解析得很好。

知道为什么一个简单的 ''' 会导致 json 无法解析吗?我在测试中遇到了与其他各种角色相同的问题。

4

1 回答 1

12

您需要将 设置Content-LengthbyteLength

res.writeHead(200, {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(write)
});

因为它会不同于String length

console.log('bar’s answer'.length);             // 12
console.log(Buffer.byteLength('bar’s answer')); // 14

这是因为,使用UTF-8 编码Node 的默认值),只有当字符串完全由ASCII 码点(U+0000 - U+007F) 组成时,它们才会匹配,而此字符串包含U+2019,“单曲线引用,对。” 超出该范围,代码点会根据需要扩展到多个字节——在 U+2019 的情况下为 3:

[ 0xE2, 0x80, 0x99 ]
于 2013-02-05T05:20:58.870 回答