从简单的 POST 请求到 node.js 的响应中出现“意外的输入结束”消息

2024-04-25

我编写了一个简单的 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 的高级 Rest 客户端对此进行 POST 时,我收到 200 OK 响应,但在响应内容的 JSON 选项卡中,出现术语“意外的输入结束”而不是解析的 json。

在原始选项卡中,显示字符串“{”foo”:“bar’s answer”,这使得 json 无法解析的原因变得显而易见(它缺少结尾的“}”)。

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

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


您需要设置Content-Length to the byteLength http://nodejs.org/api/buffer.html#buffer_class_method_buffer_bytelength_string_encoding反而:

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编码 http://en.wikipedia.org/wiki/UTF-8 (节点默认值 http://nodejs.org/api/buffer.html#buffer_new_buffer_str_encoding),只有当字符串完全由以下组成时它们才会匹配ASCII 码位 http://en.wikipedia.org/wiki/ASCII(U+0000 - U+007F),而该字符串包含U+2019 http://unicode.org/cldr/utility/character.jsp?a=2019, "单弯引号,右 http://en.wikipedia.org/wiki/Quotation_mark_glyphs#Quotation_marks_in_Unicode超出该范围,代码点将根据需要扩展到多个字节 - 在 U+2019 的情况下为 3 个字节:

[ 0xE2, 0x80, 0x99 ]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从简单的 POST 请求到 node.js 的响应中出现“意外的输入结束”消息 的相关文章

随机推荐