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".
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!

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

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

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

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

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

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'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

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
