1, the project frequently uses the HTTP send request processing data. Most of the requests are get and post, so the HTTP request is encapsulated to provide the utilization of the code.
2, Nodegress is a request tool for Nodejs.
The specific steps and code are as follows:
1, install Nodegrass, execute npm install Nodegrass command.
2, the packaging process exists using the Data Collection tool underscore tool, first installed.
3. The post and get codes in Nodegrass are as follows:
NodeGrass.prototype.get =function(Url,callback, Reqheaders, CharSet) {varprotocol =getprotocol (URL); var_defaultcharset = ' UTF8 '; if(typeofCharSet = = = ' String ') {_defaultcharset=CharSet; } if(typeof(reqheaders) = = = "string" && charset = = =undefined) {_defaultcharset=reqheaders; } varNewheader = {}; if(Reqheaders!== undefined &&typeof(reqheaders) = = = "Object") { for(varEleinchreqheaders) {newheader[ele.tolowercase ()]=Reqheaders[ele]; }} newheader["Content-length"] = 0; varOptions ={host:gethost (URL), Port:getport (URL), Path:getpath (URL), method:' GET ', Headers:newheader}; if(protocol = = = HTTP | | protocol = = =HTTPS) { return_sendreq (Protocol,NULL, Options,_defaultcharset,callback); }Else{ Throw"Sorry,this protocol don't Support Now"; }}//Post Method Request//Support HTTP and HTTPS request,and Automatic recognition//@Param URL//@Param Callback//@Param Header//@param postdataNodeGrass.prototype.post =function(url,callback,reqheaders,data,charset) {varprotocol =getprotocol (URL); var_defaultcharset = ' UTF8 '; if(typeofCharSet = = = ' String ') {_defaultcharset=CharSet; } if(typeof(data) = = = ' object ') {data =querystring.stringify (data);} varoptions={host:gethost (URL), Port:getport (URL), Path:getpath (URL), method:' POST ', headers:reqheaders}; if(protocol = = = HTTP | | protocol = = =HTTPS) { return_sendreq (protocol,data,options,_defaultcharset,callback)}Else{ Throw"Sorry,this protocol don't Support Now"; }}
4, the specific encapsulation of HTTP, the code is as follows:
varng = require ('Nodegrass');var$ = require ('Underscore');varDomain ='http://www.*******.com'; Exports.header= { 'Content-type':'application/x-www-form-urlencoded'};exports.Get=function (URL, data, success) {Ajax (URL,'Get', data, success);}; Exports.post=function (URL, data, success) {Ajax (URL,'Post', data, success);}; function ajax (URL, HttpMethod, data, success) {varargs =[Function (res, status, headers) {Try { varJSON =Json.parse (RES); Success (JSON, headers); } Catch(ex) {if(res.success) Console.log ('Ajax fail:%s', URL); }}, Exports.header]; if(HttpMethod = ='Get') {args.unshift ([domain, URL,'?', $.map (data, function (V, k) {return[K, V].join ('='); }). Join ('&')].join ("')); } Else{data._="'; Args.unshift (Domain+URL); Args.push (data); } Args.push ('UTF8'); Ng[httpmethod].apply (Ng, args). On ('Error', function () {Console.log ('Ajax Error:%s', URL); });}
Based on the code of the specific post and get request in Node-grass, the Ajax is modeled as encapsulated.
1, generally for a fixed URL prefix request, direct domain definition.
2. Each request has a fixed header tag.
3, HTTP contains get, POST request two ways.
4. HTTP contains
URL: Request Address,
Httpmothed: Request Method (Post,get)
Data: Request
Success: callback function for success or not execution
5, in which the data splicing method uses "?", "&" characters for splicing processing.
6. The character set "UTF8" must also be marked
7, at the same time there are errors when you need to output the error message prompt.
Example of a specific invocation, the code is as follows:
var ajax = Require ('./ajax ');
function (resp) { if (! resp.success) { console.log ("error"); } Console.log ("Success"); });
This makes it easy and fast to simulate requests to process the corresponding data.
The above examples are written according to Nodegrassapi, if there are deficiencies, please forgive.
Example of a simple encapsulation HTTP request using Nodegrass