Moment For Technology

Translation of Axios Chinese documents

Posted on May 27, 2023, 8:29 p.m. by 高靜宜
Category: The front end Tag: node.js The front end axios promise


Version: v0.16.1

Promise is based on HTTP clients for browsers and NodeJS

The original

Click to view the original article


  • The browser initiates the XMLHttpRequests request
  • The Node sends an HTTP request
  • Supporting Promise API
  • Intercept requests and returns
  • Converting requests and returning (data)
  • Cancel the request
  • Automatically convert JSON data
  • Client support against XSRF (Cross-site request Forgery)

The installation

Use NPM:

$ npm i axiosCopy the code

Use the bower

$ bower instal axiosCopy the code

Use the CDN

! - domestic bootCDN -- -- 
script src=""/scriptCopy the code

The sample

Make a GET request

// Initiate a user request with the given ID
axios.get('/user? ID=1234').then(function(respone){
    console.log(response); }).catch(function(error){

// The above request can also be written in the following way
        console.log(response); }).catch(function(error){
        console.log(error)});Copy the code

Make a POST request'/user',{
    console.log(response); }).catch(function(error){
});Copy the code

Initiate multiple concurrent requests

function getUserAccount(a){
    return axios.get('/user/12345');

function getUserPermissions(a){
    return axios.get('/user/12345/permissions');

        // Both requests are now complete
    }));Copy the code

axios API

There are some Settings you can make to AxiOS to generate the request.


// Initiate a POST request

    method:'post'./ / method
    url:'/user/12345'./ / address
    data: {/ / parameters
        firstName:'Fred'.lastName:'Flintstone'}});Copy the code
// Get the remote image by request
    .then(function(response){'ada_lovelace.jpg'))})Copy the code


// make a GET request axios('/user/ 12345 /);
Copy the code

Request a rename of the method.

For convenience, Axios provides renaming support for all requested methods








Pay attention to

The URL,method, and data attributes do not need to be specified in config when renaming methods.

Concurrent Concurrency

Useful method



Create an instance

You can create a new instance using custom Settings


var instance = axios.create({
});Copy the code

Instance methods

Some example methods are listed below. The specific Settings will be merged in the instance Settings.








Requese Config Request Settings

Below are some of the options for setting the request. Only the URL is required, and if method is not specified, the default request method is GET.

    // 'url' is the server link used for the request
    url:'/user'.// 'method' is the request method when the request is initiated

    // 'baseURL' will be preceded if the url is not an absolute address.
    // This is handy when Axios uses relative addresses
    // The method in the example
    baseURL:''.// 'transformRequest' allows requested data to be transformed before being sent to the server.
    // This applies only to the 'PUT', 'GET', 'PATCH' methods.
    // The last function in the array must return either a string or an ArrayBuffer, or a Stream, an instance of Buffer, ArrayBuffer, FormData
        // Process the requested data according to your own requirements
        returndata; }].// 'transformResponse' allows returned data to be processed before it is passed to then/catch
        // Process the data as needed
        returndata; }].// 'headers' is a custom header to be sent

    // 'params' is the request parameter in the request connection and must be a pure object or URLSearchParams object
    // 'paramsSerializer' is an optional function that is used to serialize parameters
    / / such as: (,
    paramsSerializer: function(params){
        return Qs.stringify(params,{arrayFormat:'brackets'})},// 'data' is the data that needs to be set for the request
    // Apply only to application 'PUT','POST','PATCH' request methods
    // When 'transformRequest' is not set, it must be one of the following types (non-repeatable?) :
    //-string,plain object,ArrayBuffer,ArrayBufferView,URLSearchParams
    //- Browser only: FormData,File,Blob
    //- only Node: Stream
    // 'timeout' defines the time of the request in milliseconds.
    // If the request time exceeds this set time, the request will stop.
    timeout:1000.// 'withCredentials' indicates whether the protocol is accessed across websites,
    // Certificates should be used
    withCredentials:false / / the default value

    // Adapter adaptor, which allows custom processing of requests, which makes testing easier.
    // Return a promise and provide validation returns (see [Response docs](#response-api))
        / *... * /

    // 'auth' indicates that HTTP-based authentication should be used and certificates provided.
    // This sets an authorization header and overrides the authorization header you set in the header.

    // 'responseType' indicates the data types returned by the server. These types should be set to
    responsetype:'json'.// 'xsrfHeaderName' is the name of the HTTP header that carries the value of XSRF
    xrsfHeadername:'X-XSRF-TOKEN'./ / the default value

    // 'onUploadProgress' allows handling of events in the upload process
    onUploadProgress: function(progressEvent){
        // What you want to do when a local process event occurs

    // 'onDownloadProgress' allows handling of events during the download process
    onDownloadProgress: function(progressEvent){
        // What you want to do during the download

    // 'maxContentLength' defines the maximum amount of HTTP content to return
    maxContentLength: 2000.// 'validateStatus' defines resolve and reject for promises.
    // HTTP returns a status code. If 'validateStatus' returns true (or null/undefined), PROMISE will accept. Other promises will be rejected.
    validateStatus: function(status){
        return status = 200  stauts  300;/ / the default

    // 'httpAgent' and 'httpsAgent' define a custom proxy for an HTTP or HTTPS request, respectively, in nodeJS.
    // This allows setting a few options, such as' keepAlive '- this is disabled by default.
    httpAgent: new http.Agent({keepAlive:treu}),
    httpsAgent: new https.Agent({keepAlive:true}),

    // 'proxy' defines the server host name and port number.
    // 'auth' indicates that HTTP basic authentication should be connected to 'proxy' and provide a certificate.
    // This will set a 'proxy-authorization' header, overwriting the original custom.
        host:127.0. 01.,
            password:'123456'}},// 'cancelTaken' defines a cancellation that can be used to cancel the request
    // (See the details of The Cancellation below)
    cancelToken: new CancelToken(function(cancel){})}Copy the code

Returns the Response Schema

The return of a request contains the following information

    //`data`Is the reply (as opposed to the request) provided by the server data{},//`status`Is the HTTP status code returned by the serverstatus:200.//`statusText`Is HTTP status information returned by the serverstatusText: 'ok'.//`headers`Is the HEADERS carried in the server returnheaders:{},

    //`config`Is set to Axios for requestconfig:{}}Copy the code

Using then, you receive the following information

    });Copy the code

When a catch is used, or a Reject callback is passed as the second argument to a THEN, the returned error message can be used.

Default Settings (Config Default)

You can set a default setting that will work on all requests.

The Global default setting is Global AXIOS Defaults

axios.defaults.baseURL = '';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;['Content-Type'] ='application/x-www-form-urlencoded';Copy the code

Example Custom instance default

Var is set by default when creating an instance instance = axios.create({ baseURL:'' }); / / change the default value after the instance creation mon [' Authorization '] = AUTH_TOKEN;Copy the code

Run the Config order of precedence command to set precedence

The Settings (Config) will be consolidated in order of priority. The first is the default Settings defined in lib/defaults.js, the second is the Settings of the defaults instance properties, and the last is the Settings of the config parameters in the request. The higher the level, the higher the level, overrides the previous Settings. Look at this example:

// Create an instance using the default library Settings. // In this instance, use the default library timeout setting, which defaults to 0. var instance = axios.create(); / / override the default repository timeout defaults / / at this point, all the request timeout time is 2.5 second instance. Defaults. Timeout = 2500; Instance. get('/longRequest',{timeout:5000});Copy the code

The interceptor interceptors

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

// Add a request interceptor
    Do something before the request is sent
    return config;
    // Do something when a request error occurs
    return Promise.reject(error);

// Add a return interceptor
    // Do some processing on the returned data
    return response;
    // Do some processing for the returned error
    return Promise.reject(error);
});Copy the code

If you need to remove the interceptor later, you can

var myInterceptor = axios.interceptors.request.use(function(a){/ *... * /});
axios.interceptors.rquest.eject(myInterceptor);Copy the code

You can use interceptors in an axios instance

var instance = axios.create(); instance.interceptors.request.use(function(){/*... * /});Copy the code

Handling Errors

axios.get('user/12345').catch(function(error) {if(error.response){
            // There is a request, but the server returns a status code
            // They are all outside 2xx
            // Some errors are triggered when setting up the request
    });Copy the code

You can customize the error range of the HTTP status code using the validateStatus setting option.

        return status  500;If the return code is less than or equal to 500, it is an error}});Copy the code

Cancel the Cancellation

You can cancel a request using the Cancel token

The axioscancel tokenThe API is based on ** CNacelable Promises Proposal **, which is currently in the first phase.Copy the code

You can create a cancel token using the canceltoken. source factory function as follows:

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/user/12345', {
        console.log('Rquest canceled', thrown.message);
        //handle error}});// Cancel the request (info parameter setting is configurable)
source.cancel("Operation cancelled by user");Copy the code

CancelToken You can create a cancel token by passing an executor function to the CancelToken constructor:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
    cancelToken: new CancelToken(function executor(c){
        // This executor function takes a cancel function as an argumentcancel = c; })});// Cancel the request
cancel();Copy the code
Note: You can use the samecancel tokenCancel multiple requests.Copy the code

Use Application/X-www-form-urlencoded formatting

By default, AXIos concatenates JS objects in JSON format. To send Application/X-WWw-form-urlencoded data, you can use the following Settings.

The Browser Browser

In the browser you can use the URLSearchParams API as follows:

var params = new URLSearchParams();
params.append('param2'.'value2');'/foo'.params);Copy the code

Note: URLSearchParams does not support all browsers, but there is a poly fill available (make sure the shipper is in the browser global environment)

Other methods: You can use the QS library to format data.

var qs = require('qs');'/foo', qs.stringify({'bar':123}));Copy the code


In NodeJS, you can use queryString as follows:

var querystring = require('querystring');'', querystring.stringify({foo:'bar'}));Copy the code

You can also use the QS library.


Axios is based on the native ES6 Promise implementation. Use gaskets if the environment does not support them.


Axios contains TypeScript definitions

import axios from 'axios'
axios.get('/user? ID=12345')Copy the code

Special paper

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.