Roh*_*han 4 html javascript node.js
我从Node.js服务器提供HTML页面并在浏览器控制台上收到此错误 -
未声明HTML文档的字符编码.如果文档包含US-ASCII范围之外的字符,则文档将在某些浏览器配置中使用乱码文本进行渲染.必须在文档或传输协议中声明页面的字符编码.
我之前已经问过这个问题,但大多数(如果不是全部)解决方案建议将此行添加到HTML文件中 -
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
Run Code Online (Sandbox Code Playgroud)
我已经尝试过这个并不适合我.
这是我的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);
.
.
.
Run Code Online (Sandbox Code Playgroud)
在before和after日志消息得到正确打印.我已经验证我的HTML文件是utf-8编码的.
有什么建议 ?
只是为了结束这个问题.
为了消除警告"未声明HTML文档的字符编码.",你需要在HTML文件的标题部分声明你的字符集.
<meta charset="UTF-8">
Run Code Online (Sandbox Code Playgroud)
此外,它应该是该部分中的第一行,如果不是第一行.
尝试:
response.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});
Run Code Online (Sandbox Code Playgroud)
如果您注意到,meta您发布的标签包含该charset属性。浏览器使用它来识别字符编码。该meta标记是事后尝试模拟Content-TypeHTTP 响应标头中通常应包含的内容。如上所示修改代码将在 HTTP 响应标头中包含信息,这是首选方法。