gpt4 book ai didi

post - POST 数据中的 node.js 和 utf-8

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:19 25 4
gpt4 key购买 nike

在使用 Node.JS 网络服务器时,我在解码 POST 数据中的 UTF-8 字符串时遇到问题。

查看这个完整的测试用例:

require("http").createServer(function(request, response) {

if (request.method != "POST") {

response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
response.end('<html>'+
'<head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head>'+
'<body>'+
'<form method="post">'+
'<input name="test" value="Grüße!"><input type="submit">'+
'</form></body></html>');

} else {

console.log("CONTENT TYPE=",request.headers['content-type']);

var body="";
request.on('data', function (data) {
body += data;
});

request.on('end', function () {
console.log("POST BODY=",body);

response.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
response.end("POST DATA:\n"+body+"\n---\nUNESCAPED:\n"+unescape(body)+
"\n---\nHARDCODED: Grüße!");
});

}

}).listen(11180);

这是一个独立的网络服务器,它在端口 11180 上监听并发送一个 HTML 页面,该页面具有一个简单的表单,其中包含一个带有特殊字符的输入字段。将该表单发布到服务器将在纯文本响应中回显其内容。

我的问题是特殊字符在控制台和浏览器中都没有正确显示。这是我在 FireFox 和 IE 上看到的:

POST DATA:
test=Gr%C3%BC%C3%9Fe%21
---
UNESCAPED:
test=GrüÃe!
---
HARDCODED: Grüße!

最后一行是一个硬编码字符串 Grüße!,它应该与输入字段的值匹配(以验证它不是显示问题)。显然,POST 数据未被解释为 UTF-8。当使用 require('querystring') 将数据分成字段时,也会出现同样的问题。

有什么线索吗?

在 Debian Linux 4 上使用 Node.JS v0.4.11,源代码以 utf-8 字符集保存

最佳答案

在 ascii 字符集中找不到 üß UTF-8 字符,并且由多个 ascii 字符表示。

根据 http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

将表单上的 enctype 切换为多部分 <form method="post" enctype="multipart/form-data />"将正确地将文本呈现为 UTF-8 字符。然后您必须解析多部分格式。 node-formidable似乎是最流行的库。

使用decodeURIComponent() 可能更简单正如你在评论中提到的。 Unescape 不处理多字节字符,而是将每个字节表示为它自己的字符,因此您看到的是乱码。 http://xkr.us/articles/javascript/encode-compare/

您还可以使用缓冲区来更改编码。在这种情况下矫枉过正,但如果您需要:

new Buffer(myString, 'ascii').toString('utf8');

关于post - POST 数据中的 node.js 和 utf-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7806960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com