首頁  >  文章  >  web前端  >  node http get 亂碼怎麼辦

node http get 亂碼怎麼辦

藏色散人
藏色散人原創
2022-12-29 16:10:152391瀏覽

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影片教學

以上是node http get 亂碼怎麼辦的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn