zoukankan      html  css  js  c++  java
  • Node响应中文时解决乱码问题

    场景

    在使用node响应英文时可以在app.js中这样写

    //代码块: node-http-server
    
    //表示引入http模块
    var http = require('http');
    /*
        request    获取客户端传过来的信息
        response  给浏览器响应信息
    */
    http.createServer(function (request, response) {
    
      //设置响应头
      response.writeHead(200, {'Content-Type': 'text/plain'});
      //表示给我们页面上面输出一句话并且结束响应
      response.end('Hello World ');
    }).listen(8081);  //端口
    
    console.log('Server running at http://127.0.0.1:8081/');

    但是如果想响应中文,即将代码改为如下

    //代码块: node-http-server
    
    //表示引入http模块
    var http = require('http');
    /*
        request    获取客户端传过来的信息
        response  给浏览器响应信息
    */
    http.createServer(function (request, response) {
    
      //设置响应头
      response.writeHead(200, {'Content-Type': 'text/plain'});
      //表示给我们页面上面输出一句话并且结束响应
      response.end('霸道的程序猿');
    }).listen(8081);  //端口
    
    console.log('Server running at http://127.0.0.1:8081/');

    运行效果

    注:

    博客:
    https://blog.csdn.net/badao_liumang_qizhi
    关注公众号
    霸道的程序猿
    获取编程相关电子书、教程推送与免费下载。

    实现

    可以通过如下两行设置响应头

    res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"}); //解决乱码
    
    res.write("<head> <meta charset='UTF-8'></head>");  //解决乱码

    完整示例代码

    const http =require('http');
    
    /*
        req   获取客户端传过来的信息
        res  给浏览器响应信息
    */
    
    http.createServer((req,res)= >{
    
        console.log(req.url);  //获取url
    
        //设置响应头
        //状态码是 200,文件类型是 html,字符集是 utf-8
        res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"}); //解决乱码
    
        res.write("<head> <meta charset='UTF-8'></head>");  //解决乱码
    
        res.write('公众号:霸道的程序猿');
    
        res.write('<h2>公众号:霸道的程序猿</h2>');
    
        res.end();  //结束响应
    
    }).listen(3000);

    效果

    博客园: https://www.cnblogs.com/badaoliumangqizhi/ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。
  • 相关阅读:
    hadoop生态--ElasticSearch--ES操作
    Haoop生态--ElasticSeaarch(1)--ES预备知识(全文检索的概念、Lucence、倒排索引)
    hadoop生态--Hive(2)--Hive的使用方式
    hadoop生态--Zookeeper
    gsoap使用
    set容器
    如何杀死defunct进程
    关于多态
    数组类型与函数指针基本语法知识
    syslog日志
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/13401204.html
Copyright © 2011-2022 走看看