解决 Node.js 程序输出中文时出现乱码的问题
修改2.1节中的例2.1的代码,将输出内容修改为中文,代码如下:
//加载http模块
var http = require('http');
console.log("请打开浏览器,输入地址 http://127.0.0.1:3000/");
//创建http服务器,监听网址127.0.0.1 端口号3000
http.createServer(function(req, res) {
res.end('明日科技');
console.log("right");
}).listen(3000,'127.0.0.1');
在 WebStorm
中运行上面代码,单击服务器结果中提示的网址,效果如图2.15所示。

Figure 1. 图2.15 Node.js 程序输出中文时出现乱码
通过观察图2.15,可以发现 Node.js 在默认输出中文时会出现乱码问题,这时可以使用 response
对象的 writeHead()
方法在输出内容之前将要显示网页的编码方式设置为 UTF-8
。
【例2.2】在 Node.js 程序中输出中文。(实例位置:资源包\源码\02\02)
要想让 Node.js 程序输出中文,只需要在输出内容之前将要显示网页的编码方式设置为 UTF-8
,代码如下:
//加载http模块
var http = require('http');
console.log("请打开浏览器,输入地址 http://127.0.0.1:3000/");
//创建http服务器,监听网址127.0.0.1 端口号3000
http.createServer(function(req, res) {
res.writeHead(200,{"content-type":"text/html;charset=utf8"}); //设置编码方式
res.end('明日科技');
console.log("right");
}).listen(3000,'127.0.0.1');
再次在 WebStorm
中运行程序,效果如图2.16所示。

Figure 2. 图2.16 在 Node.js 程序中输出中文