axios Chinese documents

axios Chinese documents

Welcome to axios. This document will help you get started quickly.

What is axios?

Axios is a promise based HTTP library that can be used in browsers and node JS.

axios

Axios is a promise based HTTP library that can be used in browsers and node JS.

characteristic

Create XMLHttpRequests from the browser
From node JS create http request
Promise API supported
Intercept requests and responses
Convert request data and response data
Cancel request
Automatically convert JSON data
Client support defense XSRF

Browser support

Chrome Firefox Safari Opera Edge IE
Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔ 8+ ✔

install

Use npm:

npm install axios

Using bower:

bower install axios

Using cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

case

Execute GET request

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

// The above request can do the same
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Execute POST request

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (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) {
    // Both requests are now complete
  }));

axios API

The request can be created by passing the relevant configuration to axios

axios(config)

// Send POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// Get remote picture
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

axios(url[, config])

// Send GET request (default method)
axios('/user/12345');

Alias of the request method

For convenience, aliases are provided for all supported request methods

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

be careful
When using alias methods, the attributes url, method, and data do not have to be specified in the configuration.

Concurrent

Helper function for handling concurrent requests

axios.all(iterable)
axios.spread(callback)

Create instance

You can create a new axios instance using custom configuration

axios.create([config])

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

Example method

The following are the available example methods. The specified configuration will be merged with the configuration of the instance.

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])

Request configuration

These are the configuration options available 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 for the request
  url: '/user',

  // `Method ` is the method used when creating the request
  method: 'get', // default

  // `baseURL 'will be automatically added before' URL ', unless' URL' is an absolute URL.
  // It can set a 'baseURL' to facilitate the delivery of relative URL s for axios instance methods
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest ` allows you to modify the request data before sending it to the server
  // It can only be used in the request methods of 'PUT', 'POST' and 'PATCH'
  // The function in the following array must return a string, or ArrayBuffer, or Stream
  transformRequest: [function (data, headers) {
    // Arbitrary conversion of data
    return data;
  }],

  // `transformResponse ` it is allowed to modify the response data before passing it to then/catch
  transformResponse: [function (data) {
    // Arbitrary conversion of data
    return data;
  }],

  // `headers ` is the custom request header to be sent
  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
  // (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 the data sent as the request body
  // Only applicable 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 specific: FormData, File, Blob
  // -Node exclusive: Stream
  data: {
    firstName: 'Fred'
  },

  // `Timeout ` specifies the number of milliseconds that the request times out (0 means no timeout)
  // If the request takes longer than 'timeout', the request will be interrupted
  timeout: 1000,

   // `withCredentials ` indicates whether credentials are required for cross domain requests
  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 ` indicates that HTTP basic authentication should be used and credentials should be provided
  // This will set an 'Authorization' header, overwriting any existing custom 'Authorization' header set with 'headers'
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

   // `responseType ` indicates the data type of the server response. It can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

   // `Xsrfcookie name ` 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 carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

   // `onUploadProgress ` allows processing progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress ` allows processing 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 whether the status code for a given HTTP response is resolve or reject promise. If 'validateStatus' returns' true' (or set to 'null' or 'undefined'), promise will be resolved; Otherwise, promise will be rejecte d
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects ` is defined in node Maximum number of redirects for follow in JS
  // If set to 0, no redirection will follow
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent 'and' httpsAgent 'are on node JS is used to define the custom proxy used when executing http and https. Allow options to be configured like this:
  // `keepAlive ` is 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 ` indicates 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 by using the '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 later for more information)
  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 the server response
  status: 200,

  // `statusText ` HTTP status information from the server response
  statusText: 'OK',

  // `headers ` the header of the server response
  headers: {},

   // `config ` is the configuration information provided for the request
  config: {},
 // 'request'
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

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

When using catch or passing rejection callback as the second parameter of then, the response can be used through the error object, as described in the error handling section.

Configure defaults

You can specify the configuration defaults that will be used for each request

Global axios default

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 defaults

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Priority of configuration

Configurations are merged in one order of priority. The order is: in lib / defaults JS, then the defaults attribute 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
// At this time, the default value of timeout configuration is ` 0`
var instance = axios.create();

// Override library timeout defaults
// Now, all requests wait 2.5 seconds before timeout
instance.defaults.timeout = 2500;

// Override timeout settings for requests that are known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});

Interceptor

Intercept requests or responses before they are processed by then or catch.

// Add request interceptor
axios.interceptors.request.use(function (config) {
    // What to do before sending the request
    return config;
  }, function (error) {
    // What to do about request errors
    return Promise.reject(error);
  });

// Add response interceptor
axios.interceptors.response.use(function (response) {
    // Do something about the response data
    return response;
  }, function (error) {
    // Do something about response errors
    return Promise.reject(error);
  });

If you want to remove the interceptor later, you can do this:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

You can add interceptors for custom axios instances

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

error handling

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Y can use the validateStatus configuration option to define an error range for custom HTTP status codes.

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

cancel

Use cancel token to cancel the request

Axios' cancel token API is based on the cancelable promises proposal, which is still in its first stage.

You can use canceltoken The source factory method creates a cancel token, like this:

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

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
     // Processing error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// Cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

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

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // The executor function takes a cancel function as an argument
    cancel = c;
  })
});

// cancel the request
cancel();

Note: you can use the same cancel token to cancel multiple requests

Use application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects into JSON. To send data in 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:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

Note that all browsers do not support URLSearchParams (see caniuse.com), but you can use polyfill (make sure to populate the global environment).

Alternatively, you can use the qs library to encode data:

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

Or in another way (ES6),

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

Node.js

In node JS, you can use the querystring module, as shown below:

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

You can also use the qs library.

Semver

Before axios reaches version 1.0, disruptive changes will be released in a new minor version. For example, 0.5 1 and 0.5 4 will have the same API, but 0.6 0 will have significant changes.

Promises

axios is supported by relying on the native implementation of ES6 Promise If your environment does not support ES6 Promise, you can use polyfill

TypeScript

axios includes TypeScript definitions.

import axios from 'axios';
axios.get('/user?ID=12345');

Keywords: Front-end axios

Added by Janco on Sat, 25 Dec 2021 15:27:51 +0200