解决中文乱码问题
- 在服务器默认发送的数据,其实是 utf-8编码的内容
- 但是浏览器不知道你是utf-8编码的内容
- 浏览器在不知道服务器响应内容的编码的情况下,会按照操作系统的默认编码去解析
- 中文操作系统默认是 gbk
- 解决方法:正确告诉浏览器我给你发送的内容是什么编码的
- 在http协议中 ,Content-Type就是用来告知对方我给你发送的数据是什么类型
- 不同文件类型对应的Content-Type 参考:https://tool.oschina.net/commons
var http = require('http');
var server = http.createServer();
server.on('request',function (req,res){
console.log('收到请求');
var url = req.url;
if(url === '/plain'){
res.setHeader('Content-Type','text/plain; charset=utf-8');
res.end('普通文本');
}else if(url === '/html'){
res.setHeader('Content-Type','text/html; charset=utf-8');
res.end('<button>hello html</button><a href="">点我</a>');
}else{
res.end('404 not found');
}
});
server.listen(5000,function (){
console.log('服务器启动了');
});