【问题标题】:How to handle utf-8 encoded text in Nodejs?如何在 Nodejs 中处理 utf-8 编码的文本?
【发布时间】:2014-12-30 09:06:27
【问题描述】:

我正在尝试将文本从提供的 HTML 表单发送到服务器。我的问题是文本似乎仍然在某种程度上以 utf8 编码?我不确定如何将文本解码回原来的形式?

html 文件

var body = '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'<form action="/upload" method="post">'+  //sends POST req to /upload
'<textarea name="text" rows="20" cols="60"></textarea>'+
'<input type="submit" value="Submit text" />'+
'</form>'+
'</body>'+
'</html>';

server.js

    req.setEncoding('utf8');

    var postData = [];
    req.on('data', function(postDataChunk) {
     // called when a new chunk of data was received
     postData.push(postDataChunk);
     console.log('Recieved POST data chunk: "'+ postDataChunk + '"');
    });

    req.addListener('end', function() {
    // called when all chunks of data have been received
    var text = decoder.write(postData);
    console.log("all Data arrived: " + text);

    route(pathname, handle, res, text);
    });

打印出:“所有数据到达:text=blah+blah+blah%21”

我已经尝试将响应的内容标头设置为 UTF-8 和 StringDecoder,如下所示,但似乎都没有做任何事情。

【问题讨论】:

  • 所以我们很清楚,您期望它提供什么?您返回的内容 (text=blah+blah+blah%21) 是 utf8 文本,但是由于您是通过表单提交的,因此它被发送到编码为 application/x-www-form-urlencoded 的服务器。通常你会用body-parser这样的东西来解码。
  • 啊,所以表单有自己的编码。我期待它回馈“等等等等!”。查找并阅读w3.org/TR/html401/interact/forms.html#h-17.13.4.1,现在我将研究body-parser。谢谢!
  • 是的,文本编码与表单值的表示方式无关。但是,服务器需要某种方式来知道哪些值映射到哪些键,因为表单可能不仅有一个 text 字段。

标签: javascript node.js character-encoding


【解决方案1】:

你可以试试

var querystring = require("querystring")

var text = querystring.parse(postData).text;
console.log("all Data arrived: " + text);

我不知道这个 postData.push 是否有效。作为替代方案,您也可以尝试:

var postData = "";
req.on('data', function(postDataChunk) {
  postData += postDataChunk;

【讨论】:

    猜你喜欢
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多