axios uses documentation

Keywords: axios JSON npm JQuery



##Axios





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

Features

  • Create from Browser XMLHttpRequests
  • Create from node.js http request
  • Support Promise API
  • Intercept requests and responses
  • Transform request and response data
  • Cancel Request
  • Automatically convert JSON data
  • Client Support Defense XSRF

Browser support

Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔ 8+ ✔

install

Use npm:

$ npm install axios

Use bower:

$ bower install axios

Use cdn:

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

Example

Execute GET Request

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

// Optionally, the above request can do so
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 executed
  }));

axios API

Requests can be created by passing configurations to axios

axios(config)
// Send POST Request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
axios(url[, config])
// Send GET requests (default method)
axios('/user/12345');

Alias of 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.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
NOTE

When using the alias method, the properties url, method, data do not have to be specified in the configuration.

Concurrent

Assistant functions for handling concurrent requests

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

Create an instance

You can create a new axios instance using a custom configuration

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

Instance Method

The following are available sample 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#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])

Request Configuration

These are the configuration options available when creating requests.Only URLs are required.If no method is specified, the request will be used by default get method.

{
  // `url` is the server URL used for requests
  url: '/user',

  // `method` is the method used to create the request
  method: 'get', // The default is get

  // `baseURL` will automatically precede `url', unless `url` is an absolute URL.
  // It can easily pass relative URLs for axios instances by setting a `baseURL`
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest`Allows modifying request data before sending it to the server
  // Can only be used with'PUT','POST'and'PATCH' request methods
  // Functions in subsequent arrays must return a string, or ArrayBuffer, or Stream
  transformRequest: [function (data) {
    // Any conversion of data

    return data;
  }],

  // `transformResponse`Allow modification of response data before passing to then/catch
  transformResponse: [function (data) {
    // Any conversion of data

    return data;
  }],

  // `headers` is the custom request header to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` is the URL parameter that will 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 subject of the request
  // 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 the request timed 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 underlying authentication should be used and provides credentials
  // This will set a `Authorization'header, overwriting any existing customizations that use `headers` settings`Authorization`headers
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` represents the data type of the server response and 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 allowed response content
  maxContentLength: 2000,

  // `validateStatus` Defines a resolve or reject promise for a given HTTP response status code.If `validateStatus` returns `true'(or is set to `null` or `undefined`), the promise will be resolved; otherwise, the promise will be rejecte d
  validateStatus: function (status) {
    return status >= 200 && status < 300; // Default
  },

  // `maxRedirects`Defines the maximum number of follow ers redirected in node.js
  // If set to 0, no redirection will be follow ed
  maxRedirects: 5, // Default

  // `httpAgent` and `httpsAgent` are used in node.js to define a custom proxy to use when executing http and https, respectively.Allow configuration options 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 underlying authentication should be used for connection broker 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 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 server response
  status: 200,

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

  // `headers`Headers of server responses
  headers: {},

  // `config` is the configuration information provided for the request
  config: {}
}

When using the then, you will receive the following responses:

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 pass rejection callback As the second parameter of the then, the response can be used through the error object, as in error handling What this section says.

Configured defaults/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 Default

// Set default values for configuration when creating instances
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Modify the default value after the instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Priority of configuration

Configurations are merged in a priority order.This order is: the default value of the library found in lib/defaults.js, then 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 default values for the configuration provided by the library
// The default value for timeout configuration is `0`
var instance = axios.create();

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

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

Interceptor

Intercept requests or responses before they are processed by the 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) {
    // What to do with response data
    return response;
  }, function (error) {
    // What to do about response errors
    return Promise.reject(error);
  });

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

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

You can add interceptors for custom axios instances

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

error handling

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was sent, but the status code of the server response is not in the 2xx range
      console.log(error.response.data);
      console.log(error.response.status);
      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);
  });

You can define a custom HTTP status code error range using the validateStatus configuration option.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Status code reject s when greater than or equal to 500
  }
})

cancel

Cancel the request using cancel token

Axios cancel token API is based on cancelable promises proposal It is still in its first phase.

CancelToken.source factory method can be used to create cancel token, like this:

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 {
    // Handling errors
  }
});

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

You can also create cancel token by passing an executor function to CancelToken's constructor:

var CancelToken = axios.CancelToken;
var cancel;

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

// Cancel Request
cancel();

Note: Multiple requests can be canceled using the same cancel token

Semver

Until axios reaches a 1.0 release, breaking changes will be released with a new minor version. For example 0.5.1, and 0.5.4 will have the same API, but 0.6.0 will have breaking changes.

Promises

axios relies on the native ES6 Promise implementation and Supported.
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');

Resources

Credits

axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular.

Posted by DaveSamuel on Wed, 29 May 2019 10:34:33 -0700