节点查询字符串解析和字符编码。

时间:2014-05-28 09:19:07

标签: javascript node.js

我有这段代码:

var qs = require('querystring');
var http = require('http');

http.createServer(function (req, res) {

    if ('/' == req.url) {
        res.writeHead(200, { 'Content-Type': 'text/html'});
        res.end([
            '<form method="post" action="/url">',
            '<h1>My form</h1>',
            '<fieldset>',
            '<label>Personal information</label>',
            '<p>What is your name?</p>',
            '<input type="text" name="name">',
            '<p><button>Submit</button></p>',
            '</form>'
        ].join(''));
    } else if ('/url' == req.url && 'POST' == req.method) {
        var body = '';

        req.on('data', function (chunk) {
            body += chunk;
        });

        req.on('end', function () {
            res.writeHead(200, { 'Content-Type': 'text/html'});
            res.end('<p>Your name is: <strong>' + qs.parse(body).name + '</strong></p>');
        });
    }
}).listen(3000);

假设我在输入字段中写了我的瑞典名字“AndersÖstman”,并在表格中张贴。一切似乎都很好,除了我的名字输出为Anders�stman。 charatcher“Ö”被删除......我想这与字符编码有关,我需要设置/转换解析后的对象为UTF-8。

问:有没有办法将qs.parse()直接导入UTF-8对象?或者对象没有编码?我输出它时是否需要对对象值进行编码?

3 个答案:

答案 0 :(得分:1)

要确保浏览器发送正确编码的表单数据,请尝试添加显式编码标头:

res.writeHead(200, { 'Content-Type': 'text/html; charset=UTF-8'});

要调试此功能,请尝试添加

 console.log(body)

到第二个分支。如果它说

name=Anders+%D6stman

浏览器仍在发送Latin-1(这是错误的)。它应该是

name=Anders+%C3%96stman

答案 1 :(得分:1)

您需要将两者的Content-Type 格式更改为text/html; charset=utf-8的POST响应。之后你会看到预期的结果(我在本地测试过):

var qs = require('querystring');
var http = require('http');

http.createServer(function (req, res) {

    if ('/' == req.url) {
        res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8'});
        res.end([
            '<form method="post" action="/url">',
            '<h1>My form</h1>',
            '<fieldset>',
            '<label>Personal information</label>',
            '<p>What is your name?</p>',
            '<input type="text" name="name">',
            '<p><button>Submit</button></p>',
            '</form>'
        ].join(''));
    } else if ('/url' == req.url && 'POST' == req.method) {
        var body = '';

        req.on('data', function (chunk) {
            body += chunk;
        });

        req.on('end', function () {
            res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8'});
            res.end('<p>Your name is: <strong>' + qs.parse(body).name + '</strong></p>');
        });
    }
}).listen(3000);

您也可以将html中的字符集设置为meta中的<head>标记:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

或HTML5:

<meta charset="utf-8">

答案 2 :(得分:0)

似乎这是缓存中的一些问题或者类似的问题...我试过在另一个浏览器中,它有效。然后我删除了chrome的总缓存,并让它在那里工作!

相关问题