如何在Nodejs中处理utf-8编码的文本?

时间:2014-12-30 00:53:27

标签: javascript node.js character-encoding

我正在尝试将提供的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设置如下,但似乎都没有做任何事情。

1 个答案:

答案 0 :(得分:0)

你能试试吗

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;