How to encode HTTP response body as UTF-8 in node.js

This is currently all the node.js server code:

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);

Based on my understanding of the node.js documentation, the second argument to 'utf8' for resp.write () should force node to encode the html string as UTF-8, and not UTF-16, which JavaScript strings are originally represented as. However, when I point my browser to localhost: 80, look at the source code and save it in a local html file, Notepad ++ tells me that the file is encoded in UTF-16. In addition, when I run it through the W3C HTML code checker, he also complains about "The declaration of the internal encoding utf-8 is not consistent with the actual encoding of the document (utf-16)."

How to force node.js to encode the HTTP response body as UTF 8?

+4
3

, :

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

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

HTTP- :

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

utf-8 IE8. 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);

, IE8 HTML-.

+1

, , , ... Internet Explorer. Internet Explorer 11 - View Source UTF-16 . , localhost utf16, google.com utf16 .. .. Firefox utf8, .

I did not believe them when they said that IE is a terrible browser. I think we all need to learn some time :(

0
source

All Articles