AXIOS study notes use method tutorial

Introduction

recently are learning Axios, Axios I believe we all know that is a promise based on the HTTP library, you can use the browser and node.js in. Therefore, this article will detail the content on Axios to use it, learn to share for your reference, the following did not talk much to say, to take a look at the detailed description:

Axios Github

features

  • created XMLHttpRequests from the browser
  • create http request from node.js
  • support the Promise API
  • interception request and response
  • convert request data and the response data
  • cancellation request
  • autochanger JSON data
  • client support defense XSRF

mounting

use bower:

  $ bower install axios  

use npm:

  $ npm install axios  

Example

performing a GET request

  // to a given user ID creation request axios.get ( '/ user? ID = 12345 ') .then (function (response) {console.log (reSponse);}) .catch (error) {console.log (error);}); // Optionally, the above request can do Axios.get ('/ user', {params: {id: 12345}}) .Then (response) {console.log (response);}) .catch (error) {console.log (error);});  

Execute POST request

  AXIOS.POST ('/ user', {firstname: 'flintstone'}) .Then (Function) Response) {console.log (response);}) .catch (error) {console.log (error);});  

Execute 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 are now executed}));   
AXIOS API

can be passed to AXIOS Configuration to create request

AXIOS (CONFIG) // Send POST request AXIOS ({Method: ‘POST’, URL: ‘/ user / 12345’, data: {FIRSTNAME : ‘Fred’, lastname: ‘flintstone’}}; AXIOS (URL [, Config]) // Send GET Request (Default Method) AXIOS (‘/ User / 12345’);
   The alias of the request method is convenient, providing alias 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]])]]]
   Note When using an alias method, these properties do not have to be configured Present specified. 

Assistant function for processing concurrent request


AXIOS.ALL (ITERABLE) AX

   
can create a custom configuration to create a new AXIOS instance

AXIOS.CREATE ([Config]) var instance = apios.create ({baseURL: ‘https://some-domain.com/api/ “Timeout: 1000, Headers : {‘X-Custom-Header’: ‘FOOBAR’}});

Example method

 It is an example method available. The specified configuration will be combined with the instance   
AXIOS # Request (config) AXIOS # get (URL [, config]) AXIOS # delete (url [, config]) Axios # Head (URL [, config]) AXIOS # pos (URL [, Data [, config]]) AXIOS # put (URL [, Data [, config]]) AXIOS # patch (url [, data [, config]])

Requests

These are configuration options that can be used when creating a request. Only URL is required. If you do not specify Method, the request will use the get method by default.
 {// `URL` is the server URL URL: '/ user', //` Method for the request.Is the method used when creating a request Method: 'get', // The default is get // `baseurl` More an absolute URL will be automatically added to the` URL` is an absolute URL. // It can pass the way to make the AXIOS instance method by setting a `baseURL` More https://some-domain.com/api///some-domain.com/api/` TRANSFORMREQUEST` Allows the modification request before sending to the server Data // can only be used in the 'Put', 'POST' PAST 'PATCH' These functions in the following array must return a string, or arraybuffer, or stream transformrequest: [Function (data) {/ / For any conversion processing Return Data;}], // `TransformResponse. //` TRANSFORMRESPONSE` More TransformResponse: [Function (data) {// is allowed to change the response data before passing to the THEN / CATCH; ], // `Headers` is a custom request header Headers: {'x-request'}, //` paramst '}, // `params` is the URL parameter / / must be sent with the request A Plain Object (Plain Object) or UrlsearchParams object params: {ID: 12345}, // `paramsserializer` is a function responsible for` params` serialized // (EG https://www.npmjs.com/package/ QS, http://///Api.jquery.com/jquery.param/) Paramsserializer: Function (params) {return qs.stringify (params, {arrayformat: 'brackets'})}, // `Data` is the data sent as a request body //// Only for these requests 'Put', 'POST', and 'Patch' // Must be one of the following types: // - String, Plain Object, ArrayBuffer, ArrayBufferView, UrlsearchParams /// - Browser exclusive: FormData, file, blob // - Node exclusive: stream data: {firstname: 'fred'}, // `Timeout` specifies the number of milliseconds request timeout (0 means no timeout time) // If the request The time exceeds `Timeout`, the request will be interrupted Timeout: 1000, //` WithCredentials`s indicates whether the transfers need to use the credentials withcredentials: false, // default // `adapter` Allow custom processing requests, Make the test more easily // returns a promise and apply a valid response (check [Response DOCS]). Adapter: Function (config) {/ * ... * /}, // `Auth` Indicates that HTTP base verification should be used, and provide credentials // This will set up a `Authorization` head, overwrite custom`, you've overwriting an existing anywhere`1orization` head auth: {username: 'janedoe', password: 's00pers3cret'}, // `responseType` indicates the data type of the server response, can be 'arraybuff', 'document', 'json', ' Text ',' Street ', // Default // `xsrfcookiename` is the name of the cookie used as the value of xsrf token xsrfcookiename:' xsrf-token ', // default //` xsrfheadername` is a bearer XSRF token's value of the HTTP header name xsrfheadername: 'x-xsrf-token', // default // `OnuploadProgress` allows for upload processing progress event onuploadprogress: function (progressevent) {// Treatment of native progress Events} , // `OndownloadProgress` Allows the Download Process Event OndownloadProgress: Function (ProgressEvent) {// The maximum size of the allowed response content}, //` MaxContentLength` defines the maximum size of the allowable response MaxContentLength: 2000, // `Validatestatus `Define the given HTTP response status code is Resolve or Reject Promise. If `validatestatus` Return` True` (or set to `null` or` undefined`), promise will be resolve; otherwise, PrOMISE will be responded by rejecte validatestatus: function (status) {return status> = 200 && status   

A request response contains the following information

{// `Data` supplied by the server response Data: {}, //` Status`s HTTP status from the server response Code Status: 200, // `statustext`s HTTP status information from the server response Statustext: ‘OK’, //` Headers: {}, // `config` is the configuration information provided for the request. Config : {}}
 When using THEN, you will receive the following response:  < 300; // 默认的
 },

 // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
 // 如果设置为0,将不会 follow 任何重定向
 maxRedirects: 5, // 默认的

 // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
 // `keepAlive` 默认没有启用
 httpAgent: new http.Agent({ keepAlive: true }),
 httpsAgent: new https.Agent({ keepAlive: true }),

 // 'proxy' 定义代理服务器的主机名称和端口
 // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
 // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
 proxy: {
 host: '127.0.0.1',
 port: 9000,
 auth: : {
 username: 'mikeymike',
 password: 'rapunz3l'
 }
 },

 // `cancelToken` 指定用于取消请求的 cancel token
 // (查看后面的 Cancellation 这节了解更多)
 cancelToken: new CancelToken(function (cancel) {
 })
} 
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);};

When using catch, or transmitting the REJECTION CALLBACK as the second parameter of the THEN, the response can pass through Error Objects can be used, just if this is wrongThe section said. .
Configuration default / defaults

You can specify the default value will be used in the configuration of 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 value  
// Setting the default value VAR Instance = AXIOS.CREATE ({baseURL: ‘https: // API) when the instance is created. EXAMPLE.COM ‘}; // Modify the default value after instance INSTANCE.DEFAULTS.HEADERS.COMMON [‘ Authorization ‘] = auth_token;



Configuration priority The order configuration will be merged in a priority order. This order is: the default value of the library found in lib / defaults.js, then the default attribute of the instance, and finally the requested config parameter. The latter will take precedence over the former. Here is an example:

// Use the default value of the configuration provided by the library to create an instance // The default value of the timeout configuration is `0`var instance =Axios.create (); // Oversurcase value of the overwriting library // Now, all requests will wait for 2.5 seconds instance.defaults.timeout = 2500; / / for a long time for a long time. Writing timeout setting instance.get (‘/ longRequest’);

Interceptor

Intercept them before the request or response is treated by THEN or CATCH.
   // Add request interceptor AXIOS.ISTERCEPTORS.REQUEST.USE (Function (config) {// What to do before sending requests Return Config;}, Function Error) {// What to do any Return Promise.reject (Error);}); // Add Response Interceptor AXIOS.ISTERCEPTORS.RESPONSE.USE (FUNCTION (response) {// Response data Do something Return Response;}, function (error) {// What to do {r响 错 错 错 什么;}; 

If you want to move later In addition to the interceptor, it can be:

VAR MyInterceptors.Request.interce (Function () {/*…*/ u u; (ketios.interceptors) .Request.eject(MyInterceptor);
   

VAR Instance = AXIOS.CREATE ( ); instance.interceptors.Request.Use (Function () {/*…*/};
error handling

AXIOS.GET (‘/ user / 12345’) .catch (error) {if (error.response) {// request has been issued, but server response The status code is not in the 2xx range console.log (Error.Response.data); console.log (error.Response.headers);} else {// Something happened in setting up The Request That Triggered An Error Console.log (‘Error’, Error.Message);} Console.log (Error.config);};

ValidateStatus can be used The configuration option defines an error range of a custom HTTP status code.
  AXIOS.GET ('/ user / 12345 ", {ValidateStatus: function (status){Return STATUS  
Canceled

Using Cancel token cancel request
  AXIOS Cancel Token API is based on Cancelable Proposal, it is still in the first phase.  
Can be created using the CancelToken.Source factory method, like this:

VAR CancelToken = Axios.canceltoken; var source = cankeke. Source (); AXIOS.GET (‘/ user / 12345’, {cazCeltoken: Source.Token}). Catch (in (thrown) {if (Axios.Iscancel (thrown)) {console.log (‘Request Canceled “, “} else {// handling error}}); // Cancel request (the Message parameter is optional) Source.Cancel (‘Operation Canceled by the user.’);
   
can also create Cancel token:


VAR CancelToken; Var CancelToken; Var CancelToken; Var CancelToken; Var CancelToken; .get (‘/ user / 12345 “, {cANCELTOKEN: New CancelToken (Function Executor (c) {// Executor function receives a Cancel function as parameter ca Zancel = C;}}); // Cancel request ca ZANCEL ();

  Note: You can use the same Cancel token to cancel multiple requests  
Excerpted from Axios Github

Summary

The above is all of this article Content, I hope this paper will bring some help to everyone’s learning or work. If you have any questions, you can leave a message, thank you for your support of Tumi Cloud.
                     
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment