解决方案
在sever.on中加入以下代码
response.writeHead(200, { ‘Content-Type‘: ‘text/plain;charset=utf-8‘ })
案例
1 var http = require(‘http‘) 2 3 var sever = http.createServer() 4 5 sever.on(‘request‘, function (request, response) { 6 7 //将响应编码设置为UTF-8,以解决乱码问题 8 response.writeHead(200, { ‘Content-Type‘: ‘text/plain;charset=utf-8‘ }) 9 console.log(‘接收到客户端的请求‘ + request.url) 10 11 switch (request.url) { 12 case ‘/‘: 13 response.write(‘主页‘) 14 break 15 case ‘/reg‘: 16 response.write(‘注册页面‘) 17 break 18 case ‘/login‘: 19 response.write(‘登录页面‘) 20 break 21 default: 22 response.write(‘404‘) 23 } 24 25 response.end() 26 }) 27 28 sever.listen(3000, function () { 29 console.log(‘服务器已启动,请访问3000端口...‘) 30 })