如何在node.js中将HTTP响应主体编码为UTF-8

时间:2013-10-12 20:49:13

标签: javascript node.js utf-8

这是我的整个node.js服务器代码:

require('http').createServer(function (req, resp) {
    var html = [
        '<!DOCTYPE html>',
        '<html>',
            '<head>',
                '<meta charset="utf-8" />',
                '<title>Sample Response</title>',
            '</head>',
            '<body>',
                '<p>Hello world</p>',
            '</body>',
        '</html>'
    ].join('');

    resp.writeHead(200, {
        'Content-Length': Buffer.byteLength(html, 'utf8'),
        'Content-Type': 'application/xhtml+xml;'
    });
    resp.write(html, 'utf8');
    resp.end();
}).listen(80);

根据我对node.js文档的理解,resp.write()的第二个'utf8'参数应该使节点将html字符串编码为UTF-8,而不是JavaScript字符串本身表示的UTF-16如。但是,当我将浏览器指向localhost:80时,查看源代码并将其保存到本地html文件,Notepad ++告诉我该文件是以UTF-16编码的。此外,当我通过W3C html验证器工具运行它时,它还抱怨“内部编码声明utf-8不同意文档的实际编码(utf-16)”。

如何强制node.js将我的HTTP响应主体编码为UTF 8?

3 个答案:

答案 0 :(得分:15)

也许你必须这样做:

'Content-Type': 'application/xhtml+xml; charset=utf-8'

答案 1 :(得分:7)

根据:https://www.w3.org/International/articles/http-charset/indexhttps://en.wikipedia.org/wiki/List_of_HTTP_header_fields

推荐HTTP标头如下所示:

"Content-Type: text/html; charset=utf-8"

使用以下两个代码,可以使用IE8浏览器在utf-8中录制。 即使法语XP32不允许在记事本++中显示泰语字符。

简短形式:

var http = require('http');

var server = http.createServer(function(req, res) {
    var body = '<p>Hello Döm</p>\n \
  <p>How are you ?</p>\n \
  <p>ผมหมาป่า(I am The Wolf)</p>';

  res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});
  res.write(body, "utf-8");
  res.end(); 
});

server.listen(8080);

长篇:

var http = require('http');

var server = http.createServer(function(req, res) {
  res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});

  var title = 'Sample Response'
  var body = '<p>Hello Döm</p>\n \
  <p>How are you ?</p>\n \
  <p>ผมหมาป่า(I am The Wolf)</p>';

  var code =  [
        '<!DOCTYPE html>',
        '<html>',
            '<head>',
                '<meta charset="utf-8" />',
                '<title>' + title + '</title>',
            '</head>',
            '<body>',
                body,
            '</body>',
        '</html>'
    ].join('\n');

  res.write(code, "utf8");
  res.end(); 
});

server.listen(8080);

如果我在HTML页面中从IE8录制,泰语字符保存得很好。

答案 2 :(得分:0)

信不信由你,我在互联网上遇到的这个问题是由于...... Internet Explorer。在这种情况下,Internet Explorer 11出于某种原因认为无论原始页面编码是什么,都可以保存UTF-16中View Source窗口的结果。所以,我从localhost的测试页面保存为utf16,google.com保存为utf16等。安装Firefox及其utf8就眼睛所见。

当他们说IE是一个糟糕的浏览器时,我不相信他们。我想我们都要学习一些时间:(