React HTTP request, native HTTP request encapsulation

Source: Internet
Author: User
Tags file upload http request json

React not like angular's $resource or $http, or jquery's $ajax-like network request library, the network request is the author's own encapsulation, of course, you can also adapt according to their own needs.


The main content is get,post,jsonp and file upload several formats


Request example, which may have used my other package service, please ignore:

Httpservice.query ({
    URL: '/api/active/follow ',
    data: {
        extendKey:CommonService.getUrlParams (' Extendkey '), this
        . Props.dstuin
    },
    success:res = {
        Console.log (res);
         (Res.retcode = = 0) {This
            . SetState ({
                true
            })
         {
            r_uiservice.toaster (res.retmsg)}}
);


If it is a POST request or JSONP, it is similar. The following is the source code, if there is a special need, you can also make their own transformation. Source code can not be used directly in the ES5 environment, need to compile through Babel, recommend the use of gulp or Webpack

/** * Created by Sheldon on 2016/8/2. */' use strict ';classHttpservice {StaticQuery (config) {config = config | | {};varparams = Httpservice.formatparams (Config.data);varRequest =NewXMLHttpRequest (); Request.onreadystatechange =function() {if(Request.readystate = = 4) {varstatus = Request.status;if(Status >= && status < 300) {varres = Json.parse (request.responsetext);
                Config.success && config.success (res); }Else{returnConfig.fail && config.fail (status);
        }
            }
        }; Request.open (' GET ', Config.url + "?" + params,true); Request.send (NULL); }StaticJsonp (config) {config = config | | {};varparams = Httpservice.formatparams (Config.data);varScrip=document.createelement (' script '); SCRIP.SRC = Config.url + "?" + params + ' &jsoncallback= ' + ' httpservice.jsonpcallback '; This. callback = config.success;
    Document.body.appendChild (Scrip); }StaticJsonpcallback (e) { This. Callback (e); }StaticSave (config) {config = config | | {};varparams = Httpservice.formatparams (Config.data);varRequest =NewXMLHttpRequest (); Request.onreadystatechange =function() {if(Request.readystate = = 4) {varstatus = Request.status;if(Status >= && status < 300) {varres = Json.parse (request.responsetext);
                    Console.log (RES);
                Config.success && config.success (res); }Else{Config.fail && config.fail (status);
        }
            }
        }; Request.open ("POST", Config.url,true);
        Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
    Request.send (params); }StaticUploadFile (CFG) {varConfig = cfg | | {};varXhrvarFileobj = Config.file; JS Get File Objectvarurl = config.url; Receive the background address of the uploaded filevarform =NewFormData (); FormData Object Form.append (Config.name, fileobj); File Object XHR =NewXMLHttpRequest (); XMLHttpRequest Object Xhr.open ("Post", URL,true);
        Post method, URL is the server request address, true This parameter specifies whether the request is processed asynchronously. Xhr.onreadystatechange =function() {if(Xhr.readystate = = 4) {varstatus = Xhr.status;if(Status >= && status < 300) {varres = Json.parse (xhr.responsetext);
                    Console.log (RES);
                Config.success && config.success (res); }Else{Config.fail && config.fail (status);
        }
            }
        }; Xhr.send (form); Start upload, send form data}StaticFormatparams (data) {vararr = []; for(varNameinchData) {Arr.push (encodeURIComponent (name) + "=" + encodeURIComponent (Data[name])); } Arr.push (("v=" + math.random ()). Replace (".", ""));returnArr.join ("&"); }
}


Have a question welcome to the Exchange

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.