搜索
首页web前端前端问答node http get 乱码怎么办

node http get 乱码怎么办

Dec 29, 2022 pm 04:10 PM
node乱码

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
CSS:我可以在同一DOM中使用多个ID吗?CSS:我可以在同一DOM中使用多个ID吗?May 14, 2025 am 12:20 AM

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

HTML5的目的:创建一个更强大,更容易访问的网络HTML5的目的:创建一个更强大,更容易访问的网络May 14, 2025 am 12:18 AM

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互动,可及可访问。1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

HTML5的重要目标:增强网络开发和用户体验HTML5的重要目标:增强网络开发和用户体验May 14, 2025 am 12:18 AM

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒体综合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityAncccossibility.2)和TagsallowsemplowsemplowseamemelesseamlessallowsemlessemlessemelessmultimedimeDiaiiaemediaiaembedwitWithItWitTplulurugIns.3)

HTML5:安全吗?HTML5:安全吗?May 14, 2025 am 12:15 AM

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrevulnerabilityLikeClickLickLickLickLickLickjAckJackJacking.2)

与较旧的HTML版本相比,HTML5目标与较旧的HTML版本相比,HTML5目标May 14, 2025 am 12:14 AM

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

CSS:使用ID选择器不好吗?CSS:使用ID选择器不好吗?May 13, 2025 am 12:14 AM

使用ID选择器在CSS中并非固有地不好,但应谨慎使用。1)ID选择器适用于唯一元素或JavaScript钩子。2)对于一般样式,应使用类选择器,因为它们更灵活和可维护。通过平衡ID和类的使用,可以实现更robust和efficient的CSS架构。

HTML5:2024年的目标HTML5:2024年的目标May 13, 2025 am 12:13 AM

html5'sgoalsin2024focusonrefinement和optimization,notnewfeatures.1)增强performandemandeffifice throughOptimizedRendering.2)risteccessibilitywithrefinedibilitywithRefineDatientAttributesAndEllements.3)expliencernsandelements.3)explastsecurityConcerns,尤其是withercervion.4)

HTML5试图改进的主要领域是什么?HTML5试图改进的主要领域是什么?May 13, 2025 am 12:12 AM

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供应,2)语义结构,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,简化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)