设置响应数据的类型
- 在服务器默认发送的数据,其实是utf-8编码的内容
- 浏览器在不知道服务器响应内容的情况下会按照当前操作系统的默认编码去解析
- 中文操作系统默认是gbk
- 解决方法:正确地告诉浏览器,服务器响应的内容是什么编码的
- 在http协议中,Content-type 就是用来告知浏览器,响应的数据类型
编码:
1 var http=require('http') 2 3 var server=http.createServer() 4 5 server.on('request',function(req,res){ 6 var url=req.url 7 if(url=='/plain'){ 8 res.setHeader('Content-type','text/plain;charset=utf-8') 9 res.end('hello 世界1') 10 }else if(url=='/html'){ 11 res.setHeader('Content-type','text/html;charset=utf-8') 12 res.end('<p>hello 世界2 <p>') 13 } 14 }) 15 16 server.listen(80,function(){ 17 console.log("Server is running...") 18 })
运行结果1:
运行结果2:
---