Talking about Axios

Source: Internet
Author: User

Useful in our projects:

    • Fetch
      Have a direct use, also have their own packaging after use;
    • Vue-resource
      When Vue1 is used, the method is abstracted out, it is always necessary to pass this to the method. $http, feel is a super uncomfortable design, in vue2 time discarded;
    • Axios
      This is a very good design, it is borrowed angularjs the concept of HTTP + httpbackend, the unit test,mocking data is more convenient to replace a false backend can, and code deduction comments, about 500 lines;

So now let's learn more about Axios (friend Circle has a front-end classmate called it "Artie"??)

Second, detailed Axios

1. What is Axios?

Axios is a promise-based HTTP library that can be used in browsers and node. js. (Is it based on promise's understanding of its API?) ha haha)

2. Features of the Axios

    • Create XMLHttpRequests from the browser
    • Create an HTTP request from node. js
    • Support Promise API
    • Intercept requests and responses (that is, there are interceptor)
    • Transform request data and response data
    • Cancel Request
    • Convert JSON data automatically
    • Client Support Defense XSRF

PS: Maybe you are not very familiar with interceptor (interceptor), here is the introduction, the interceptor can be sent before the request and after the request to do some processing. There is a picture that clearly understands what it did in an HTTP request, such as

Image.png

3. Compatibility

Image.png

4. Installation
Using NPM:
$ npm install axios
Using Bower:
$ bower install axios
Using a CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

5. Basic usage

Perform a GET requestMake a request for a user with a given idaxios.get ('/user?id=12345 '). Then (function (response) { Console.log (response); }). catch (function (error) { Span class= "hljs-built_in" >console.log (Error); }); //optionally the request above could also is done Asaxios.get (/ User ', {params: {id: 12345}}). Then ( Span class= "hljs-function" >function (response) {console.log (response); }). catch (function (error) { Span class= "hljs-built_in" >console.log (Error); }); 

is not all in the Then,catch processing response, feel fetch is similar, write very convenient
6. Using the process
would have liked to stick Axios API in this, which is no different from reading API documents, So here's how we use it, maybe it's more helpful to you.

//first we create a Axios instance var axiosins = axios.create ({baseurl:  ' https:// some-domain.com/api/', timeout: 1000,  Headers: { ' x-product ':  ' h5 '}}); //set the request Interceptor AxiosIns.interceptors.request.use ( request) = {//handle request here, can be processed for all requests first Class}) //Set Response Interceptor AxiosIns.interceptors.response.use ( ( response) = = {//handles response here, which is global and works for all requests that use Axios});   
You can encapsulate the creation instance and the set interceptor as a function, and then call it directly on the OKInstance methodThe following are the available instance methods. The specified configuration is merged with the configuration of the instance Axios#request (config) Axios#get (url[, config]) Axios#delete (url[, config]) Axios#head (url[, config]) Axios#post (url[, data[, config]) Axios#put (url[, data[, config]) Axios#patch (url[, data[, Config])Request Configuration {' URL ' is the URL of the server URL used for the request:'/user ',' Methods ' is the method used when creating the request:' Get ',The default is get' BaseURL ' will be automatically added to the ' URL ', unless ' URL ' is an absolute URL.It is possible to pass a relative URL BaseURL for a Axios instance by setting a ' BaseURL ' method:' https://some-domain.com/api/',' Transformrequest ' allows the request data to be modified before sending to the serverCan only be used in ' PUT ', ' POST ' and ' PATCH ' several request methodsThe function in the following array must return a string, or ArrayBuffer, or Stream transformrequest: [function(data) {Arbitrary conversion processing of datareturn data; }],' Transformresponse ' allows the response data to be modified before it is passed to Then/catch transformresponse: [function(data) {Arbitrary conversion processing of datareturn data; }],' Headers ' is the custom request header that is about to be sent headers: {' X-requested-with ':' XMLHttpRequest '},' Params ' is the URL parameter that will be sent with the requestMust be an unformatted object (plain objects) or Urlsearchparams object params: {ID:12345},' Paramsserializer ' is a function that is responsible for the ' params ' serialization(e.g. Https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) Paramsserializer:function(params) {Return Qs.stringify (params, {arrayformat:' Brackets '}),' Data ' is what is sent as the principal of the requestApply only to these request methods ' PUT ', ' POST ', and ' PATCH 'When ' transformrequest ' is not set, it must be one of the following types:-String, plain object, ArrayBuffer, Arraybufferview, Urlsearchparams-Browser-specific: FormData, File, Blob-Node Exclusive: Stream data: {firstName:' Fred '},' Timeout ' specifies the number of milliseconds the request timed out (0 means no time-out)If the request is over the time of ' timeout ', the request will be interrupted by timeout:1000,' Withcredentials ' indicates whether a credential withcredentials is required when cross-domain requests are used:FalseThe default' Adapter ' allows custom processing of requests to make testing easierReturns a promise and applies a valid response (consult [Response docs] (#response-api)). Adapterfunction(config) {/* ... */ },' Auth ' indicates that HTTP Basic authentication should be used and provide credentialsThis will set a ' Authorization ' header, overwrite any existing custom ' Authorization ' headers that use the ' headers ' setting Auth: {username:' JaneDoe ', password:' S00pers3cret '},' Responsetype ' represents the data type of the server response, which can be ' arraybuffer ', ' blob ', ' document ', ' json ', ' text ', ' Stream ' Responsetype:' JSON ',The default' Xsrfcookiename ' is the name of the cookie used as the value of XSRF token xsrfcookiename:' Xsrf-token ',Default' Xsrfheadername ' is the name of the HTTP header that hosts the value of XSRF token xsrfheadername:' X-xsrf-token ',The default' Onuploadprogress ' allows for upload processing progress event onuploadprogress:function(progressevent) {Handling of native progress events},' ondownloadprogress ' allows processing of progress events for download ondownloadprogress:function(progressevent) {Handling of native progress events},' Maxcontentlength ' defines the maximum size allowed for the response content maxcontentlength:2000,The ' validatestatus ' definition for a given HTTP response status code is resolve or reject promise. If ' validatestatus ' returns ' true ' (or set to ' null ' or ' undefined '), promise will be resolve; Otherwise, promise will be rejecte Validatestatus:function(status) {Return status >=&& Status <300;Default},' MaxRedirects ' defines the maximum number of redirects follow in node. jsIf set to 0, no redirect maxredirects will be follow:5,The default' Httpagent ' and ' httpsagent ' are used in node. js to define custom proxies to use when executing HTTP and HTTPS. Allow configuration options like this:' KeepAlive ' is not enabled by default httpagent:New HTTP. Agent ({keepAlive:true}), Httpsagent: new https. Agent ({keepAlive: true}), //' proxy ' defines the host name and port of the proxy server //' auth ' means that HTTP Basic authentication should be used for connection Broker and provide credentials //this will set a ' proxy-authorization ' Header, overwrite the existing custom ' Proxy-authorization ' header set by using ' header '. Proxy: {host:  ' 127.0.0.1 ', Port: 9000, Auth:: {username:  ' mikeymike ', Password:  ' rapunz3l '}}, //' Canceltoken ' Specifies the Cancel token //for canceling the request (see later cancellation this section learn more) Canceltoken: new canceltoken (function            

Additional notes:
XMLHttpRequest or fetch is a browser-enabled feature, and Axios is the Axios library we encapsulate

7. References
Https://github.com/mzabriskie/axios


Gas Cheng
Links: https://www.jianshu.com/p/065294e2711c

Talking about Axios

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.