当前位置: 首页 > 后端技术 > Node.js

Node封装http请求

时间:2023-04-03 17:17:56 Node.js

节点封包http请求varhttp=require("http");varurlUtil=require('url');varfile=require("./file");varquerystring=require('querystring');varHttpUtil={//get提交url,返回html数据get:function(url,success,error){http.get(url,function(res){varresult="";res.setEncoding("UTF-8");res.on("data",function(data){result+=data;});res.on('error',error);res.on('end',function(){success(result);});}).on('错误',this.requestError);},post:function(hostname,port,path,body,acceptType,contentType,success,error){varbodyString="";if(body!=null&&contentType=="application/json"){bodyString=JSON.stringify(body);}elseif(body!=null&&contentType=="application/x-www-form-urlencoded"){bodyString=querystring.stringify(body);}varopts={hostname:hostname,port:port,path:path,method:'post',headers:{'Accept':acceptType,'Content-Type':contentType,'Content-Length':bodyString.length}}varreq=http.request(opts,function(res){varresult="";res.setEncoding("UTF-8");res.on("data",function(data){result+=data;});res.on('error',error);res.on('end',function(){success(result);});});req.on('error',this.requestError);file.writeInFile(请求);req.write(bodyString);请求结束();},//提交表单参数,并返回html内容postAndReturnHtml:function(url,body,success,error){varurlConfig=urlUtil.parse(url);varcontentType="application/x-www-form-urlencoded";变量acceptType="文本/html";this.post(urlConfig.hostname,urlConfig.port,urlConfig.path,body,acceptType,contentType,success,this.responseError);},//get提交url参数,并返回json数据getAndReturnJson:function(url,success,error){this.get(url,function(data){vardata=JSON.parse(data);success(data);},this.responseError(错误));},//提交json参数,并返回jsonpostAndReturnJson:function(url,body,success,error){varcontentType="application/json";varacceptType="应用程序/json";varurlConfig=urlUtil.parse(url);this.post(urlConfig.hostname,urlConfig.port,urlConfig.path,body,acceptType,contentType,function(data){vardata=JSON.parse(data);success(data);},this.responseError(error));},requestError:function(error){console.log("请求失败--"+error.message);},responseError:function(error){返回错误||功能(e){console.log("响应失败--"+e.message);};}}module.exports=HttpUtil;更多文章