站长资讯网
最全最丰富的资讯网站

node http get 乱码怎么办

node http get乱码的解决办法:1、打开相应的react文件;2、通过“var req = http.get(url,function(res){res.setEncoding('utf-8');var html = ''res.on('data',function(data){html+=data.toString();})…”语句设置编程为“utf-8”即可。

node http get 乱码怎么办

本教程操作环境:Windows10系统、node v10.16.0版、Dell G3电脑。

node http get 乱码怎么办?

nodejs http.get乱码问题处理方法

代码如下:

var req = http.get(url,function(res){     res.setEncoding('utf-8');     var html = ''     res.on('data',function(data){         html+=data.toString();     }).on('end',function(){         console.log(html);     }) });
登录后复制

相关介绍:

http.get :

由于大多数请求都是没有主体的 GET 请求,因此 Node.js 提供了这个便捷的方法。 这个方法与 http.request() 的唯一区别是它将方法设置为 GET 并自动调用 req.end()。 注意,由于 http.ClientRequest 章节中所述的原因,回调必须注意消费响应数据。

主要用于做数据请求。

有关于http.get 代码的解读:

const http =require('http');//由于http.get是Node的http模块   所以第一件事情当然是引入http模块啦~                                  http.get('这里是你想要请求的接口地址', (res) => {//res是请求后端给你的数据                                 const { statusCode } = res;//获取请求的状态码                                  const contentType = res.headers['content-type'];//获取请求类型                                let error;                 if (statusCode !== 200) {//如果请求不成功 (状态码200代表请求成功哦那个)                   error = new Error('请求失败n' +                                     `状态码: ${statusCode}`); //报错抛出状态码                 } else if (!/^application/json/.test(contentType)) {//验证请求数据类型是否为json数据类型   json的content-type :'content-type':'application/json'                   error = new Error('无效的 content-type.n' +//再次报错                                     `期望的是 application/json 但接收到的是 ${contentType}`);                 }                 if (error) {//如果报错了                   console.error(error.message);         res.resume();//将请求的错误存入日志文件                   return;                 }                              //请求成功                 res.setEncoding('utf8');//字符编码设为万国码                 let rawData = '';//定义一个字符变量                 res.on('data', (chunk) => { rawData += chunk; });//通过data事件拼接数据流得到数据                 res.on('end', () => {//end表示获取数据结束了                   try {  //捕获错误信息                                         console.log(rawData);//输出数据                   } catch (e) {                     console.error(e.message);                   }                 });               }).on('error', (e) => {                 console.error(`出现错误: ${e.message}`);               });
登录后复制

推荐学习:《node.js视频教程》

赞(0)
分享到: 更多 (0)