nodejs中文乱码
发布于 12 年前 作者 miracleit 21611 次浏览 最后一次编辑是 8 年前
最近在研究nodejs,写了一个测试例子,结果中文都是乱码,不知如何解决
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(
'<!doctype html>'+
'<html>'+
'<head>'+
'<meta charset="gbk"/>'+
'<title>米诺</title>'+
'</head>'+
'<body>'+
'<a href="/home.js">主页</a>'+
'<a href="/contact.js">Contact</a>'+
'</body>'+
'</html>'); 
response.end(); }).listen(8888);
console.log("服务启动");

在浏览器中标题"米诺"和l链接"主页"都为乱码,控制台"服务启动"四个字显示为空行.

6 回复

把文件的编码改为utf-8

还有你文件本身的编码对不对,建议meta和文件本身编码都是utf-8

ok了,谢谢!

怎样用nodejs读取一个html文件,把html文件的内容返回到浏览器显示呢?readFile()?这个方法怎么用啊?

fs.readFile(file_path, "binary", function(err, file) {
	if (err) {
		response.writeHead(500, {
			'Content-Type': 'text/plain'
		});
		response.end(err);
	} 
	else {
		response.writeHead(200, {
			'Content-Type': 'text/html'
		});
		response.write(file, "binary");
		response.end();
	}
});
回到顶部