search
HomeWeb Front-endFront-end Q&AWhat to do if node http get is garbled?

What to do if node http get is garbled?

Dec 29, 2022 pm 04:10 PM
nodeGarbled characters

Node http get garbled solution: 1. Open the corresponding react file; 2. Pass "var req = http.get(url,function(res){res.setEncoding('utf-8') ;var html = ''res.on('data',function(data){html =data.toString();})..." statement can be programmed to "utf-8".

What to do if node http get is garbled?

The operating environment of this tutorial: Windows 10 system, node v10.16.0 version, Dell G3 computer.

What should I do if node http get is garbled?

nodejs http.get garbled problem handling method

The code is as follows:

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);
    })
});

Related introduction:

http. get:

Since most requests are GET requests without a body, Node.js provides this convenience method. The only difference between this method and http.request() is that it sets the method to GET and Automatically call req.end(). Note that due to the reasons described in the http.ClientRequest chapter, the callback must pay attention to consuming response data.

Mainly used for making data requests.

About http Interpretation of .get code:

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}`);
              });

Recommended study: "node.js Video Tutorial"

The above is the detailed content of What to do if node http get is garbled?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software