Vue Axios Full Raiders

Source: Internet
Author: User
Tags instance method

Reprint: https://www.cnblogs.com/libin-1/p/6607945.html

Introduction Method:
$ npm Install axios$ cnpm Install Axios//taobao Source $ bower Install Axios or use CDN: <  src= "Https://unpkg.com/axios/dist/axios.min.js"></script >

Give me a chestnut: Execute GET request
//Make a request to a user with the specified ID The parameter axios.get ('/user ', {params: {id:12345}}) can also be passed through the params object. Then (function (response) {Console.log ( response);}). catch (function (error) {Console.log (error);})
Perform a POST request
Axios.post ('/user ', {firstName: ' Fred ', lastName: ' Flintstone '}). Then (function (response) {Console.log (response);}). catch (function (error) {Console.log (error);});
Executing multiple concurrent Requests
function Getuseraccount () {return axios.get ('/user/12345 '),} function Getuserpermissions () {return axios.get ('/user/ 12345/permissions ');} Axios.all ([Getuseraccount (), Getuserpermissions ()]). Then (Axios.spread (function (acct, perms) {//Two requests now complete } ));
Axios API

Requests can be made by passing the relevant configuration to Axios.

Axios (config)
//Send a POST request Axios ({method: ' post ', url: '/user/12345 ', data: {firstName: ' Fred ', lastName: ' Flintstone '}});
Axios (url[, config])
//Send a GET request (GET request is the default request mode)Axios ('/user/12345 ');
Request Method Alias

For the sake of convenience, aliases have been provided for all supported request methods.

    • 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]])

Attention
When using the Alias method, you do not need to specify the Url,method and data properties in CONFIG.

Concurrent

The Help function handles concurrent requests.

    • Axios.all (iterable)
    • Axios.spread (callback)
Create an instance

You can use a custom configuration to create a new instance of Axios.

Axios.create ([config])

var instance = axios.create ({baseURL: ' https://some-domain.com/api/', timeout:1000,headers: {' X-custom-header ': ' Foobar '}});

Instance methodthe available instance methods are shown below. The specified configuration is merged with the instance configuration.

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

These are the available configuration options for making requests. Only URLs are required. If no method is specified, the request defaults to get.

{//' URL ' is the server URL that will be used for the requestURL: '/user ',The//' method ' is the request method used when making the requestMethod: ' Get ',//default//' BaseURL ' will be added to ' URL ' before, unless ' URL ' is absolute. You can easily set ' BaseURL ' for an instance of Axios to pass a relative URL to the method of that instance. BaseURL: ' https://some-domain.com/api/',//' Transformrequest ' allows the request data to be changed before it is sent to the server//This applies only to the request method ' PUT ', ' POST ' and ' PATCH '//array The last function must return a string, a Arraybuffer or a StreamTransformrequest: [function (data) {//Do whatever data you want to convertreturn data;}],//' Transformresponse ' allows changes to the response data prior to Then/catchTransformresponse: [function (data) {//Do whatever your want to transform the datareturn data;}],//' headers ' is the custom headers to be sentHeaders: {' x-requested-with ': ' XMLHttpRequest '},//' params ' is the URL parameter to be sent with the request//must be a pure object or a Urlsearchparams objectParams: {id:12345},//' Paramsserializer ' is an optional function that is responsible for serializing ' params '//(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 to be sent as the request principal///apply only to the request method "PUT", "POST" and "PATCH"//When no ' transformrequest ' is set, must be one of the following types://-String, plain Object, ArrayBuffer, Arraybufferview, urlsearchparams//-Browser only:formdata, File, blob//-Node only:streamData: {firstName: ' Fred '},//' timeout ' specifies the number of milliseconds before the request times out. If the requested time exceeds ' timeout ', the request will be aborted. timeout:1000,//' withcredentials ' indicates whether cross-site access control request//should be made using credentialsWithcredentials:false,//default//' adapter ' allows custom processing of requests, which makes testing easier. Returns a promise and provides a valid response (see [Response docs] (#response-api))Adapter:function (config) {/* ... */},//' auth ' indicates that HTTP Basic authentication should be used and provide credentials. This will set a ' Authorization ' header, overwriting any existing ' Authorization ' custom headers, using the ' headers ' setting. Auth: {username: ' janedoe ', Password: ' S00pers3cret '},//"Responsetype" indicates the type of data the server will respond to//including ' Arraybuffer ', ' blob ', ' document ', ' json ', ' text ', ' stream 'Responsetype: ' json ',//default//' Xsrfcookiename ' is the name of the cookie to be used as the value of the XSRF tokenXsrfcookiename: ' Xsrf-token ',//default//' Xsrfheadername ' is the name of the HTTP header that carries the XSRF token valueXsrfheadername: ' X-xsrf-token ',//default//' onuploadprogress ' allows processing of upload progress eventsOnuploadprogress:function (progressevent) {//Use the local progress event to do whatever you want to do},//' ondownloadprogress ' allows processing of download progress eventsOndownloadprogress:function (progressevent) {//Do whatever your want with the native Progress event},//' maxcontentlength ' defines the maximum size allowed for HTTP response contentmaxcontentlength:2000,//' Validatestatus ' defines whether a given promise//HTTP response status code is resolved or rejected. If ' validatestatus ' returns ' true ' (or is set to ' null ' promise will be parsed; otherwise, promise will be/rejected. Validatestatus:function (status) {return status >= && status<; //Default}, //' maxredirects ' defines the maximum number of redirects to follow in node. js. If set to 0, redirection is not followed. Maxredirects:5, //Default //' httpagent ' and ' httpsagent ' are used to define custom proxies that are used when executing HTTP and HTTPS requests separately in node. js. Allows you to configure options similar to ' keepAlive ',//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 auth should be used to connect to the proxy and provide credentials. This will set a ' proxy-authorization ' header, overwriting any existing ' proxy-authorization ' custom headers using ' headers ' settings. Proxy: {host:' 127.0.0.1 ',Port:9000,auth:: {username: ' mikeymike ', Password: ' rapunz3l '}}, //"Canceltoken" specifies the cancellation token that can be used to cancel the request//(see cancellation section below for details)canceltoken:new Canceltoken (function (cancel) {})}

When you use then, 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);});

Configure default values

You can specify the configuration defaults that will be applied to each request.

Global Axios Default value
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 values
//Set configuration defaults when creating an instance var instance = axios.create ({   //Change the default value after instance creation Instance.defaults.headers.common [ ' Authorization '] = Auth_token;
Configure priority order

The configuration is merged with the precedence order. The order is the library default in Lib/defaults.js, then the defaults property of the instance, and finally the Config parameter of the request. The latter will prevail over the former. Here's an example.

//Use the configuration defaults provided by the library to create an instance//At this time, the timeout configuration value is ' 0 ', which is the default value of the library //Overwrite the library's timeout default//Now all requests will wait 2.5 seconds before timing out //Overwrite this request timeout because it knows that it takes a long time to instance.get ('/Longrequest ', {   timeout:5000});
Interception device

You can intercept requests or responses before they are processed by then or catch

//Add Request Interceptor axios.interceptors.request.use (function (config) {     ////To do something before sending a request     return config;   } , function (Error) {     //Request error When doing something     return promise.reject (error);   //Add Response Interceptor Axios.interceptors.response.use (function (response) {     //To do something about the response data     return Response;   },function (Error) {     //Request error When doing something     return promise.reject (Error);   } );

You can add interceptors to a custom instance of Axios.

var myinterceptor = Axios.interceptors.request.use (function () {/*...*/}); Axios.interceptors.request.eject ( Myinterceptor);

If you may need to remove the interceptor later.

var instance = axios.create (); Instance.interceptors.request.use (function () {/*...*/});
Handling Errors
Axios.get ('/user/12345 ')   . catch (function (error) {     if (error.response) {       //request issued, but the server responds with a status code       //Fall outside       the range of 2xx Console.log (error.response.data);       Console.log (error.response.status);       Console.log (error.response.headers);     } else {       //Error       console.log (' Error ', error.message) occurred while setting the request to trigger the error.}     }     Console.log (Error.config);   } );

You can use the Validatestatus configuration option to define a custom HTTP status code error range.

axios.get ('/user/12345 ', {   validatestatus:function (status) {     <); //Reject only if the status code is greater than or equal to 500   }}) 

Eliminate

You can use the cancellation token to cancel the request.

The Axios Cancel token API is based on the promise proposal, which is currently in Phase 1.

You can use the Canceltoken.source factory to create a cancellation token, as follows:

var canceltoken = Axios. Canceltoken;var Source = Canceltoken.source (); Axios.get ('/user/12345 ', {cancelToken:source.token}). catch (function (thrown) {if (Axios.iscancel (thrown)) { Console.log (' Request canceled ', thrown.message);} else {//Handle error //Cancel request (message parameter is optional)source.cancel (' operation was canceled by user. ‘);

You can also create a cancellation token by passing the executor function to the Canceltoken constructor:

var canceltoken = Axios. Canceltoken;var Cancel; Axios.get ('/user/12345 ', {   canceltoken:new canceltoken (function executor (c)} {     //An executor function receives a cancellation function as a parameter      cancel = c;   //Cancel Request clear ();

Note: You can use the same cancellation token to cancel several requests.

Using the application/x-www-form-urlencoded format

By default, Axios serializes JavaScript objects into JSON. To send data in an application/x-www-form-urlencoded format, you can use one of the following options.

Browser

In the browser, you can use the Urlsearchparams API as follows:

var params = new Urlsearchparams ();p arams.append (' param1 ', ' value1 ');p arams.append (' param2 ', ' value2 '); Axios.post ('/ Foo ', params);


Alternatively, you can encode the data using the QS Library: Note that all browsers do not support Urlsearchparams, but there is one polyfill available (ensure that the Polyfill Global environment).

var qs = require (' qs '); Axios.post ('/foo ', qs.stringify ({' Bar ': 123});
node. jsin node. js, you can use the QueryString module as follows:
var querystring = require (' querystring '); Axios.post (' http://something.com/', querystring.stringify ({foo: ' Bar '});

You can also use the QS Library.

Promise

Axios relies on this confidential support ES6 promise implementation. If your environment does not support ES6 Promises, you can use Polyfill.

TypeScript

Axios includes typescript definitions.

Import Axios from ' Axios '; Axios.get ('/user?id=12345 ');

Axios is largely inspired by the $http services offered by angular. In the end, Axios strives to provide an independent $http-like service that is used outside the angular.

Vue Axios Full Raiders

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.