CNode

nodejs中文乱码

Mmiracleit发布于14 年前最后回复14 年前6 回复22569 浏览0 收藏
最近在研究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)

L
lizhepro#1·14 年前

把文件的编码改为utf-8

L
lambda#2·14 年前

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

M
miracleit#4·14 年前

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

S
sumory#6·14 年前
引用 miracleit怎样用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();
	}
});
参与回复
登录后即可参与回复。登录