Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The character encoding of HTML document was not declared

I am serving an HTML page from a Node.js server and get this error on the browser console -

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.

I know this question has been asked before, but most, if not all, of the solutions suggest adding this line to the HTML file -

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

I have already tried this and it doesn't work for me.

Here is my Node.js server code that serves the HTML-

var http = require('http');
var url = require('url');
var fs = require('fs');

var server = http.createServer(function(request, response) {
    console.log('connected');
    var path = url.parse(request.url).pathname;

    switch(path) {
        case "/realtime-graph-meter.html":
            fs.readFile(__dirname + path, function(error, data) {
                if(error) {
                    response.writeHead(404);
                    response.write("404 not found");
                } else {
                    console.log("before");
                    response.writeHead(200, {"Content-Type": "text/html"});
                    response.write(data, "utf-8");
                    console.log("after");
                }
            });
            break;
        default:
            response.writeHead(404);
            response.write("404 not found");
            break;
    }
    response.end();
});

server.listen(3000);
.
.
.

The before and after log messages get printed correctly. I have verified that my HTML file is utf-8 encoded.

Any suggestions ?

like image 752
Rohan Avatar asked Sep 09 '15 12:09

Rohan


1 Answers

Just to put an end to this question.

The magic spell, to get rid of the warning "The character encoding of the HTML document was not declared.", you need to declare your charset in the header section of the HTML file.

<meta charset="UTF-8">

Also, it should be one of, if not the first, line in the section.

like image 118
Mogens TrasherDK Avatar answered Oct 02 '22 02:10

Mogens TrasherDK