Nodejs http模块返回内容中文乱码问题及解决

目录
  • Nodejs http模块返回内容中文乱码
  • Nodejs 模块使用 http、url
    • 1.安装插件
    • 2.http和url模块的应用
  • 总结

Nodejs http模块返回内容中文乱码

当调用rs.end()方法,向客户端发送中文内容的时候,会出现乱码问题,此时,需要手动设置内容的编码格式:

修改完后记得重新运行代码

server.on('request', (req, res) => {
    const url = req.url
    const method = req.method
    const s = `请求的url是 ${url}, 请求方法是 ${method}`
    console.log(s)

    // 调用res.end()方法,向服务器响应一些内容
    res.setHeader("Content-Type", 'text/html; charset=utf-8')
    res.end(s)
})

可以看到返回的内容已经被修改成功

Nodejs 模块使用 http、url

1.安装插件

在vsCode中安装插件Node Snippets后,有node提示

输入node根据提示文本选择node-http-server可以快速生成请求代码

var http = require('http');
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/');

2.http和url模块的应用

url的方法:http://nodejs.cn/api/url.html

url.parse(urlString[,,])  //解析url地址
url.format()//parse的反向操作
url.resolve(from,to);//添加或者替换地址
url.resolve('/one/two/three', 'four');         // '/one/two/four'
url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
var http = require('http');//引入http模块
const url = require('url')

//http://127.0.0.1:3000?name=zhangsan&age=20   获取get传过来的值

/**
 * request 获取浏览器客户端传过来的信息
 * response服务器响应的信息
 */
http.createServer(function (request, response) {
    //设置响应头,包括状态码200,请求的文本类型,字符集是utf-8
    response.writeHead(200, {'Content-Type': 'text/html;charset="utf-8"'});

    response.write("<head><meta charset='UTF-8'></head>")//解决中文乱码

    // console.log(request.url);//获得浏览器请求的地址

    if(request.url!='/favicon.ico'){
        //避免在浏览器地址栏输入url后服务器不断返回/favicon.ico地址
        var userInfo = url.parse(request.url,true).query;
        console.log(userInfo)
        console.log(`姓名:${userInfo.name}--年龄:${userInfo.age}`)
    }

    response.end('response finish!');//结束响应,必须调用,不然浏览器回一直处于响应状态
}).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');
//var api = 'http://127.0.0.1:3000?name=zhangsan&age=20'
// console.log(url.parse(api,true));//设置为ture,将返回的值解析为对象
// var getValue=url.parse(api,true).query;
// console.log(getValue);//获得url传过来的值
// console.log(`姓名:${getValue.name}--年龄:${getValue.age}`)

运行上面代码后,在浏览器中手动输入get请求

http://127.0.0.1:3000?name=zhangsan&age=20'

命令行中能返回

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Node.js抓取中文网页乱码问题和解决方法

    Node.js 抓取非 utf-8 的中文网页时会出现乱码问题,比如网易的首页编码是 gb2312,抓取时会出现乱码 复制代码 代码如下: var request = require('request')  var url = 'http://www.163.com' request(url, function (err, res, body) {      console.log(body) }) 可以使用 iconv-lite来解决 安装 复制代码 代码如下: npm install ico

  • node.js解决客户端请求数据里面中文乱码的事件方法

    node.js解决客户端请求数据里面中文乱码的事件 例如代码: var http = require('http'); var server = http.createServer(); server.on('request',function(req,res){ // res.end("hello world"); res.end("你好 世界"); }); server.listen(3000,function(){ console.log("Serv

  • 解决nodejs中使用http请求返回值为html时乱码的问题

    今天用nodejs进行http请求时返回的数据是一个html文件,然后我还是按照以前解析json数据的方法.果不其然报错了:SyntaxError: Unexpected token  in JSON at position 0 没办法,只好换一种方法,将接受到的Buffer对象toString,然后打印出来发现是乱码. 第一感觉是编码问题,google一下然后看官方文档,总结三种方法: 1.toString 加编码格式作为参数. 2.使用iconv-lite 改变编码. 3.使用cheerio

  • Nodejs http模块返回内容中文乱码问题及解决

    目录 Nodejs http模块返回内容中文乱码 Nodejs 模块使用 http.url 1.安装插件 2.http和url模块的应用 总结 Nodejs http模块返回内容中文乱码 当调用rs.end()方法,向客户端发送中文内容的时候,会出现乱码问题,此时,需要手动设置内容的编码格式: 修改完后记得重新运行代码 server.on('request', (req, res) => { const url = req.url const method = req.method const

  • 解决flask接口返回的内容中文乱码的问题

    写一个简单的例子程序: # coding:utf-8 import flask from flask import json, jsonify, request, render_template app = flask.Flask(__name__) @app.route("/api", methods=["GET", "POST"]) def api(): if request.method == 'GET': return jsonify({

  • spring+mybatis 通过@ResponseBody返回结果中文乱码的解决方法

    问题发生: 通过@Responsebody返回 @ResponseBody @RequestMapping(value ="/selectByFormId",method = RequestMethod.GET) public Map<String,Object> getClassName(String formId){ List<String> list =formInfoService.selectClassName(formId); Map<Stri

  • 解决pycharm下os.system执行命令返回有中文乱码的问题

    如下所示: source = ['C:\\Users\\admin\\Desktop\\pythonLearning'] target_dir = 'C:\\Users\\admin\\Desktop' print(time.strftime('%Y%m%d%H%M%S')) target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' if not os.path.exists(target_dir): os.mkd

  • springboot返回前端中文乱码的解决

    尝试了各种防止中文乱码的方式,但是还是乱码;最后还是细节问题导致; 解决方式: 以及俩种方式是百度的,我的问题不是这俩块 1.在requestMapping 中添加 produces @RequestMapping( value = "/login", produces = "application/json;charset=utf-8", method = RequestMethod.POST ) 2.在application.yml 中添加配置 spring:

  • springboot与数据库返回数据中文乱码

    问题描述:使用springboot操作数据库时,返回的中文数据一直是乱码 刚开始以为是springboot的问题,一直在网上搜索springboot返回数据是乱码结果我的问题压根对不上边,怎么都解决不好 后面发现应该是mysql数据库的问题,于是上网搜索,最后判断是字符集的问题 解决流程:先使用sql语句查看数据库的字符集 show variables like 'character%'; 发现多处地方都不是utf8,想要修改的话要对mysql配置文件修改,网上很多修改都是使用命令修改,但是这种

  • PHP使用strrev翻转中文乱码问题的解决方法

    本文实例讲述了PHP使用strrev翻转中文乱码问题的解决方法.分享给大家供大家参考,具体如下: 在用PHP中的strrve翻转中文时,会出现乱码情况 例如: header("Content-Type: text/html; charset=utf-8"); echo strrev("处理使用strrev()函数时的乱码问题")."<br>"; 运行结果为: ��鮗遠籹䄚綗氕潇�)(verrts��翽䆐焤� 解决方法就是自己重写一个c

  • PHP读MYSQL中文乱码的快速解决方法

    打算切换某个网站的主机,没想到遇到Php和Mysql中文乱码的问题. 以前的国外主机用的Mysql是4.x系列的,感觉还比较好,都无论GBK和UTF-8都没有乱码,没想到新的主机的Mysql是5.0版本的,导入数据后,用Php读出来全是问号,乱码一片,记得我以前也曾经有过一次切换出现乱码的经验,原因肯定是Mysql版本之间的差异问题. 只好查资料,发现了一个解决方法,就是在mysql_connect后面加一句SET NAMES UTF8,即可使得UTF8的数据库消除乱码,对于GBK的数据库则使用

  • Linux php 中文乱码的快速解决方法

    在ubuntu下php网页输出乱码,在不涉及数据库编码的情况下: 修改"/etc/php5/apache2/php.ini"将 default_charset = "iso-8859-1" 修改为 default_charset = "utf-8" 然后重启apache: sudo /etc/init.d/apache2 restart 以上这篇Linux php 中文乱码的快速解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望

  • jsp传参 servlet接收中文乱码问题的解决方法

    在公司实习了8个月,一直都是做android和h5的,但是发现做程序连一点服务都不会该怎么办,所以最近开始学起了java,不知道是不是因为框架学多了,现在看起springmvc框架比以前看起来简单太多了,这里我是准备从hibernate开始学习,毕竟数据是根本嘛,首先我用的是hibernate+servlet,但是在jsp页面传参到servlet的时候中文一直乱码,我尝试了好多方法,最后还是解决了. 第一,首先看清项目的编码,jsp页面的编码 第二,修改tomcat 下面的server.xml文

随机推荐