Preface
I am learning Axios recently. I believe everyone knows that Axios is an HTTP library based on promises that can be used in browsers and . Therefore, this article will introduce the relevant content on how to use Axios in detail, and share it for your reference and learning. Let’s not say much below, let’s take a look at the detailed introduction together:
Axios Github
Functional Features
- Create XMLHttpRequests from the browser
- Create http request from
- Support Promise API
- Intercept requests and responses
- Convert request data and response data
- Cancel request
- Automatically convert JSON data
- Client-supported defense XSRF
Install
Use bower:
$ bower install axios
Using npm:
$ npm install axios
Example
Perform a GET request
// Create a request for the user with a given ID('/user?ID=12345') .then(function (response) { (response); }) .catch(function (error) { (error); }); // Optionally, the above request can be done like this('/user', { params: { ID: 12345 } }) .then(function (response) { (response); }) .catch(function (error) { (error); });
Perform a POST request
('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { (response); }) .catch(function (error) { (error); });
Perform multiple concurrent requests
function getUserAccount() { return ('/user/12345'); } function getUserPermissions() { return ('/user/12345/permissions'); } ([getUserAccount(), getUserPermissions()]) .then((function (acct, perms) { // Both requests are now completed }));
axios API
Requests can be created by passing relevant configuration to axios
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');
Alias of request methods for convenience, alias is provided for all supported request methods.
(config) (url[, config]) (url[, config]) (url[, config]) (url[, data[, config]]) (url[, data[, config]]) (url[, data[, config]])
NOTE When using an alias method, url, method, and data properties must not be specified in the configuration.
concurrent
Helper function for handling concurrent requests
(iterable) (callback)
Create an instance
You can create a new axios instance using custom configuration
([config]) var instance = ({ baseURL: '/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
Example method
The following are available example methods. The specified configuration will be merged with the instance's 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 configuration options that can be used when creating a request. Only url is required. If no method is specified, the request will use the get method by default.
{ // `url` is the server URL used for request url: '/user', // `method` is the method used when creating a request method: 'get', // The default is get // `baseURL` will be automatically added before `url` unless `url` is an absolute URL. // It can facilitate the passing of relative URLs to the axios instance method by setting a `baseURL` baseURL: '/api/', // `transformRequest` allows modification of request data before sending to the server // Only use the request methods of 'PUT', 'POST' and 'PATCH' // The function in the following array must return a string, or an ArrayBuffer, or a Stream transformRequest: [function (data) { // Perform arbitrary conversion of data return data; }], // `transformResponse` is allowed to modify the response data before being passed to then/catch transformResponse: [function (data) { // Perform arbitrary conversion of data return data; }], // `headers` is a custom request header to be sent soon headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` is the URL parameter to be sent with the request // Must be a plain object or URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is a function responsible for `params` serialization // (. /package/qs, //) paramsSerializer: function(params) { return (params, {arrayFormat: 'brackets'}) }, // `data` is data sent as the requesting body // Applicable 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 exclusive: FormData, File, Blob // - Node exclusive: Stream data: { firstName: 'Fred' }, // `timeout` specifies the number of milliseconds for the request timeout (0 means no timeout) // If the request charge exceeds the timeout, the request will be interrupted timeout: 1000, // `withCredentials` indicates whether credentials are required when requesting across domains withCredentials: false, // Default // `adapter` allows custom processing of requests to make testing easier // Return a promise and apply a valid response (see [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` means that HTTP basic verification should be used and credentials are provided // This will set an `Authorization` header, overwriting any existing custom `Authorization` header set using `headers` 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', // 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', // Default // `onUploadProgress` allows processing of progress events for uploads onUploadProgress: function (progressEvent) { // Handling of native progress events }, // `onDownloadProgress` allows processing of progress events for downloads onDownloadProgress: function (progressEvent) { // Handling of native progress events }, // `maxContentLength` defines the maximum size of the allowed response content maxContentLength: 2000, // `validateStatus` defines the status code for the given HTTP response to be resolve or reject promise . If `validateStatus` returns `true` (or set to `null` or `undefined`), the promise will be resolved; otherwise, the promise will be rejected validateStatus: function (status) { return status >= 200 && status < 300; // Default }, // `maxRedirects` defines the maximum number of redirects in follow // If set to 0, no redirects will be followed maxRedirects: 5, // Default // `httpAgent` and `httpsAgent` are used in ``httpsAgent` to define the custom proxy used when executing http and https, respectively. Allows configuring options like this: // `keepAlive` is not enabled by default httpAgent: new ({ keepAlive: true }), httpsAgent: new ({ keepAlive: true }), // 'proxy' defines the host name and port of the proxy server // `auth` means that HTTP basic authentication should be used for connection proxy and provide credentials // This will set a `Proxy-Authorization` header, overwriting the existing custom `Proxy-Authorization` header set using `header`. proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies the cancel token used to cancel the request // (See the Cancellation section below to learn more) cancelToken: new CancelToken(function (cancel) { }) }
Response structure
The response to a request contains the following information
{ // `data` Response provided by the server data: {}, // `status` HTTP status code from server response status: 200, // `statusText` HTTP status information from the server response statusText: 'OK', // `headers` server response header headers: {}, // `config` is the configuration information provided for the request config: {} }
When using then, you will receive a response like this:
('/user/12345') .then(function(response) { (); (); (); (); (); });
When using catch, or when passing rejection callback as the second parameter of then, the response can be used through the error object, as explained in the error handling section. .
Configuration default values/defaults
You can specify the configuration default values that will be used on each request
Global axios default value
= ''; ['Authorization'] = AUTH_TOKEN; ['Content-Type'] = 'application/x-www-form-urlencoded';
Custom instance default values
// Set the default value of the configuration when creating an instancevar instance = ({ baseURL: '' }); // Modify the default value after the instance has been created['Authorization'] = AUTH_TOKEN;
The configurations are merged in one priority. This order is: the default value of the library found in lib/, followed by the defaults property of the instance, and finally the requested config parameter. The latter will take precedence over the former. Here is an example:
// Create an instance using the default values of the configuration provided by the library// The default value of the timeout configuration at this time is `0`var instance = (); // Overwrite the timeout default value of the library// Now, before timeout, all requests wait 2.5 seconds = 2500; // Override the timeout setting for a request that takes a long time known to take('/longRequest', { timeout: 5000 });
Interceptor
Intercept requests or responses before they are processed by then or catch.
// Add a request interceptor(function (config) { // What to do before sending a request return config; }, function (error) { // What to do about the request error return (error); }); // Add a response interceptor(function (response) { // Do something about the response data return response; }, function (error) { // Do something to respond to errors return (error); });
If you want to remove the interceptor later, you can do this:
var myInterceptor = (function () {/*...*/}); (myInterceptor);
You can add interceptors to custom axios instances
var instance = (); (function () {/*...*/});
Error handling
('/user/12345') .catch(function (error) { if () { // The request has been issued, but the status code of the server response is not within the range of 2xx (); (); (); } else { // Something happened in setting up the request that triggered an Error ('Error', ); } (); });
You can use the validateStatus configuration option to define an error range for a custom HTTP status code.
('/user/12345', { validateStatus: function (status) { return status < 500; // The status code will reject only if it is greater than or equal to 500 } })
Cancel
Use cancel token to cancel the request
Axios' cancel token API is based on cancelable promises proposals, which is still in its first phase.
You can use the factory method to create a cancel token, like this:
var CancelToken = ; var source = (); ('/user/12345', { cancelToken: }).catch(function(thrown) { if ((thrown)) { ('Request canceled', ); } else { // Handle errors } }); // Cancel the request (message parameter is optional)('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the CancelToken constructor:
var CancelToken = ; var cancel; ('/user/12345', { cancelToken: new CancelToken(function executor(c) { // The executor function receives a cancel function as a parameter cancel = c; }) }); // Cancel requestcancel();
Note: You can use the same cancel token to cancel multiple requests
Excerpted from axios github
Summarize
The above is the entire content of this article. I hope that the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.