解决Node.js http响应出现乱码的问题

解决中文乱码问题

  • 在服务器默认发送的数据,其实是 utf-8编码的内容
  • 但是浏览器不知道你是utf-8编码的内容
  • 浏览器在不知道服务器响应内容的编码的情况下,会按照操作系统的默认编码去解析
  • 中文操作系统默认是 gbk
  • 解决方法:正确告诉浏览器我给你发送的内容是什么编码的
  • 在http协议中 ,Content-Type就是用来告知对方我给你发送的数据是什么类型
  • 不同文件类型对应的Content-Type 参考:https://tool.oschina.net/commons
//加载http核心模块
var http = require('http');

//创建web服务器
var server = http.createServer();

//注册请求事件,当客户端请求过来,就会自动触发服务器的request 请求事件
server.on('request',function (req,res){
    
    

console.log('收到请求');

 var url = req.url;
    if(url === '/plain'){
    
    
    
        //text/plain是普通文本
        res.setHeader('Content-Type','text/plain; charset=utf-8');
        
        res.end('普通文本');
        
    }else if(url === '/html'){
    
    
    
        //如果你要发送的是html格式的字符串,则也要告诉浏览器我给你发送的是text/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('服务器启动了');
})

猜你喜欢

转载自blog.csdn.net/cake_eat/article/details/108942026