This time to bring you axios how to promise-based HTTP request client, Axios based on the promise of the HTTP request client's considerations, the following is the actual case, together to see.
Axios
Promise-based HTTP request client that can be used in both the browser and node. js
Functional characteristics
Sending xmlhttprequests requests in the browser
Sending an HTTP request in node. js
Support Promiseapi
Intercept requests and responses
Transform request and response data
Convert JSON data automatically
Client support protects security from XSRF attacks
Browser support
Installation
Using Bower:
$ Bower Install Axios
Using NPM:
$ NPM Install Axios
Example
Send a GET request
Make a, request for a, user with a given idaxios.get ('/user?id=12345 '), then (function (response) {Console.log (response);}). catch (function (response) {Console.log (response);}); /Optionally the request above could also be do asaxios.get ('/user ', {params:{id:12345}}). Then (function (response) { Console.log (response);}). catch (function (response) {Console.log (response);});
Send a POST request
Axios.post ('/user ', {firstName: ' Fred ', lastName: ' Flintstone '}). Then (function (response) {Console.log (response);}). catch (function (response) {Console.log (response);});
Send multiple concurrent Requests
Functiongetuseraccount () {returnaxios.get ('/user/12345 ');} Functiongetuserpermissions () {returnaxios.get ('/user/12345/permissions ');} Axios.all ([Getuseraccount (), Getuserpermissions ()]). Then (Axios.spread (function (acct,perms) {//Both requests is now Complete}));
Axios API
You can customize the request by passing the corresponding parameters to the Axios:
Axios (config)//Send a post Requestaxios ({method: ' post ', url: '/user/12345 ', data:{firstname: ' Fred ', LastName: ' Flintstone '}}); Axios (url[, Config])//sned a GET request (default method) Axios ('/user/12345 ');
Request Method Alias
For convenience, we have provided aliases for all supported request methods
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])
Attention
When using the Alias method, the URL, method, and data properties do not need to be specified in the config parameter.
Concurrent
Helper methods for handling concurrent requests
Axios.all (iterable) Axios.spread (callback)
Create an instance
You can create a new Axios instance with a custom configuration.
Axios.create ([config]) varinstance=axios.create ({baseURL: ' https://some-domain.com/api/', timeout:1000,headers:{' X-custom-header ': ' Foobar '}});
Instance method
All available instance methods are listed below, and the specified configuration will be merged with the configuration of that 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
The following are the available request configuration items, only URLs are required. If no method is specified, the default request method is get.
{//' URL ' is the URL of the server that would be a used for the Requesturl: '/user ',//' method ' was the request method to being used when Making the Requestmethod: ' Get ',//default//' BaseURL ' 'll be prepended to ' url ' unless ' url ' is absolute.//It can be co Nvenient to set ' BaseURL ' for a instance of Axios to pass relative urls//to methods of the that Instance.baseurl: '//' trans Formrequest ' allows changes to the request data before it's sent to the server//it's only applicable for request meth ODS ' PUT ', ' POST ', and ' PATCH '//The last function in the array must return a string or an Arraybuffertransformrequest:[fu Nction (data) {//do whatever your want to transform the datareturndata;}],//' Transformresponse ' allows changes to the RESPO NSE data to be made before//it's passed to then/catchtransformresponse:[function (data) {//does whatever you want to Transf ORM the datareturndata;}],//' headers ' is custom headers to be sentheaders:{' x-requested-with ': ' XMLHttpRequest '},//' Params ' is the URL parameteRS to being sent with the requestparams:{id:12345},//' Paramsserializer ' is a optional function in charge of serializing ' PA Rams '//(e.g Https://www.npmjs.com/package/qs, paramsserializer:function (params) {returnqs.stringify (params,{ Arrayformat: ' brackets ')},//' data ' is the data to being sent as the request body//only applicable for request methods ' PUT ' , ' POST ', and ' PATCH '//When no ' transformrequest ' are set, must be a string, an ArrayBuffer or a hashdata:{firstname: ' Fred '},//' timeout ' specifies the number of milliseconds before the request times out.//If the request takes longer than ' Tim Eout ', the request would be aborted.timeout:1000,//' withcredentials ' indicates whether or not cross-site Access-control re quests//should be made using credentialswithcredentials:false,//default//' adapter ' allows custom handling of requests W Hich makes testing easier.//call ' resolve ' or ' reject ' and supply a valid response (see [Response docs] (#response-api)). A Dapter:function (Resolve,reject,config) {/* ... */},//' auth ' indicates that HTTP Basic auth should is used, and supplies credentials.//this would set an ' Autho Rization ' header, overwriting any existing//' Authorization ' Custom headers you have set using ' headers '. Auth:{username: ' J Anedoe ', Password: ' S00pers3cret '}//' responsetype ' indicates the type of data that the server would respond with//options a Re ' arraybuffer ', ' blob ', ' document ', ' json ', ' text ' Responsetype: ' json ',//default//' Xsrfcookiename ' is the name of the C Ookie to use as a value for XSRF tokenxsrfcookiename: ' Xsrf-token ',//default//' Xsrfheadername ' is the name of the HTTP he Ader that carries the XSRF token valuexsrfheadername: ' X-xsrf-token ',//default//' progress ' allows handling of progress EV Ents for ' POST ' and ' PUT uploads '//AS-well ' GET ' downloadsprogress:function (progressevent) {//does whatever you want wit H The native Progress event}}
Data structure of the response
The response data includes the following information:
{//' data ' is the response-provided by the serverdata:{},//' status ' is the HTTP status code from the server resp onsestatus:200,//' StatusText ' is the HTTP status message from the server responsestatustext: ' OK ',//' headers ' the headers That's the server responded withheaders:{},//' config ' is the config, that's provided to ' Axios ' for the requestconfig:{}
When you use then or catch, you receive the following response:
Axios.get ('/user/12345 '). Then (function (response) {console.log (response.data); Console.log (Response.Status); Console.log (Response.statustext); Console.log (response.headers); Console.log (response.config);});
Default configuration
You can specify a default configuration for each request.
Global Axios Default configuration
Axios.defaults.baseurl= ' https://api.example.com '; axios.defaults.headers.common[' Authorization ']=auth_token; axios.defaults.headers.post[' Content-type ']= ' application/x-www-form-urlencoded ';
Custom instance Default configuration
Set config defaults when creating the Instancevarinstance=axios.create ({baseURL: '//Alter defaults after instance have been createdinstance.defaults.headers.common[' Authorization ']=auth_token;
Prioritization of configurations
Config would be merged with an order of precedence. The order is library defaults found Inlib/defaults.js, Thendefaultsproperty of the instance, and finallyconfigargument for The request. The latter'll take precedence over the former. Here's an example.//Create a instance using the config defaults provided by the library//at the The timeout conf IG value is ' 0 ' as was the default for the Libraryvarinstance=axios.create ();//Override timeout default for the library// Now all requests would wait 2.5 seconds before timing outinstance.defaults.timeout=2500;//Override timeout for this reques T as it ' s known to take a long timeinstance.get ('/longrequest ', {timeout:5000});
Interception device
You can intercept requests and responses before processing then or catch
Add a request Interceptor Axios.interceptors.request.use (Function (config) {//do something before request is sentreturnconfig;}, Function (Error) {//do something with request Errorreturnpromise.reject (error);}); /Add a response Interceptor Axios.interceptors.response.use (function (response) {//do something with response datareturnresponse;}, Function (Error) {//do something with response errorreturnpromise.reject (error);});
To remove an interceptor:
Varmyinterceptor=axios.interceptors.request.use (function () {/*...*/}); Axios.interceptors.request.eject ( Myinterceptor);
You can add interceptors to a custom Axios instance:
Varinstance=axios.create (); Instance.interceptors.request.use (function () {/*...*/}); Error handling Axios.get ('/user/12345 ') . catch (function (response) {if (responseinstanceoferror) {//Something happened in setting up the request that triggered an E Rrorconsole.log (' Error ', response.message);} else{//the request was made and the server responded with a status code//that falls out of the range of 2xxconsole.log ( Response.data); Console.log (Response.Status); Console.log (response.headers); Console.log (response.config);}); Promisesaxios relies on a native ES6 Promise implementation, if your browser environment does not support ES6 Promises, you need to introduce Polyfilltypescriptaxios to include a typescript definition//import *asaxiosfrom ' Axios '; Axios.get ('/user?id=12345 '); Creditsaxios is heavily inspired by The$http serviceprovided Inangular. Ultimately Axios is an effort to provide a standalone$http-like service for use outside of Angular.licensemit
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Related reading:
Vue How to use Anmate.css
Gradient colors for CSS
Useful 404 Components
To solve the iview in the Vue-cli shelf font icon missing method