node.js-中文乱码解决

使用NodeJS,当有中文时,如果不做任何处理就会出现乱码。因为,NodeJS 不支持 GBK。当然,UTF-8是支持的。

所以,要确保不出现乱码,应做到以下两点:

  • 保证你的 JS文件是以UTF-8格式保存的。
  • 在你的JS文件中的 writeHead 方法中加入 "charset=utf-8" 编码,如下例所示:

var http = require("http");

 http.createServer(function (req, res) {
     res.writeHead(200, {
       "Content-Type": "text/html;charset=utf-8"
     });

      res.end("<h1>Hello World</h1>");
 }).listen(8888);
原文地址:https://www.cnblogs.com/fydxx/p/6678806.html