我正在从 Node.js 服务器提供 HTML 页面并在浏览器控制台上收到此错误 -
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.
我知道之前有人问过这个问题,但大多数(如果不是全部)解决方案都建议将这一行添加到 HTML 文件中 -
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
我已经试过了,但它对我不起作用。
这是我的 Node.js 服务器代码,用于提供 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);
.
.
.
before
和 after
日志消息得到正确打印。我已验证我的 HTML 文件是 utf-8 编码的。
有什么建议吗?
最佳答案
只是为了结束这个问题。
魔咒,要摆脱警告“未声明 HTML 文档的字符编码。”,您需要在 HTML 文件的 header 部分声明您的字符集。
<meta charset="UTF-8">
此外,它应该是该部分中的一行(如果不是第一行的话)。
关于javascript - 未声明 HTML 文档的字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32479888/