Promise based HTTP client for the browser and node.js
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Automatic transforms for JSON data
- Client side support for protecting against XSRF
![]() | ![]() | ![]() | ![]() | ![]() |
|---|---|---|---|---|
| Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 8+ ✔ |
Using bower:
$ bower install axiosUsing npm:
$ npm install axiosPerforming a GET request
// Make a request for a user with a given IDaxios.get('/user?ID=12345').then(function(response){console.log(response);}).catch(function(response){console.log(response);});// Optionally the request above could also be done asaxios.get('/user',{params: {ID: 12345}}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});Performing a POST request
axios.post('/user',{firstName: 'Fred',lastName: 'Flintstone'}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});Performing multiple concurrent requests
functiongetUserAccount(){returnaxios.get('/user/12345');}functiongetUserPermissions(){returnaxios.get('/user/12345/permissions');}axios.all([getUserAccount(),getUserPermissions()]).then(axios.spread(function(acct,perms){// Both requests are now complete}));Requests can be made by passing the relevant config to axios.
axios({method: 'get',url: '/user/12345'});For convenience aliases have been provided for all supported request methods.
When using the alias methods url, method, and data properties don't need to be specified in config.
Helper functions for dealing with concurrent requests.
You can create a new instance of axios with a custom config.
varinstance=axios.create({baseURL: 'https://some-domain.com/api/',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}});The available instance methods are listed below. The specified config will be merged with the instance config.
These are the available config options for making requests. Only the url is required. Requests will default to GET if method is not specified.
{// `url` is the server URL that will be used for the requesturl: '/user',// `method` is the request method to be used when making the requestmethod: 'get',// default// `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance.baseURL: 'https://some-domain.com/api/',// `transformRequest` allows changes to the request data before it is sent to the server// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'// The last function in the array must return a string or an ArrayBuffertransformRequest: [function(data){// Do whatever you want to transform the datareturndata;}],// `transformResponse` allows changes to the response data to be made before// it is passed to then/catchtransformResponse: [function(data){// Do whatever you want to transform the datareturndata;}],// `headers` are custom headers to be sentheaders: {'X-Requested-With': 'XMLHttpRequest'},// `param` are the URL parameters to be sent with the requestparams: {ID: 12345},// `paramsSerializer` is an optional function in charge of serializing `params`// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)paramsSerializer: function(params){returnQs.stringify(params,{arrayFormat: 'brackets'})},// `data` is the data to be sent as the request body// Only applicable for request methods 'PUT', 'POST', and 'PATCH'// When no `transformRequest` is set, must be a string, an ArrayBuffer or a hashdata: {firstName: 'Fred'},// `timeout` specifies the number of milliseconds before the request times out.// If the request takes longer than `timeout`, the request will be aborted.timeout: 1000,// `withCredentials` indicates whether or not cross-site Access-Control requests// should be made using credentialswithCredentials: false,// default// `adapter` allows custom handling of requests which makes testing easier.// Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)).adapter: function(resolve,reject,config){/* ... */},// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.// This will set an `Authorization` header, overwriting any existing// `Authorization` custom headers you have set using `headers`.auth: {username: 'janedoe',password: 's00pers3cret'}// `responseType` indicates the type of data that the server will respond with// options are 'arraybuffer', 'blob', 'document', 'json', 'text'responseType: 'json',// default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName: 'XSRF-TOKEN',// default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName: 'X-XSRF-TOKEN'// default}The response for a request contains the following information.
{// `data` is the response that was provided by the serverdata: {},// `status` is the HTTP status code from the server responsestatus: 200,// `statusText` is the HTTP status message from the server responsestatusText: 'OK',// `headers` the headers that the server responded withheaders: {},// `config` is the config that was provided to `axios` for the requestconfig: {}}When using then or catch, you will receive the response as follows:
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);});You can intercept requests or responses before they are handled by then or catch.
// Add a request interceptoraxios.interceptors.request.use(function(config){// Do something before request is sentreturnconfig;},function(error){// Do something with request errorreturnPromise.reject(error);});// Add a response interceptoraxios.interceptors.response.use(function(response){// Do something with response datareturnresponse;},function(error){// Do something with response errorreturnPromise.reject(error);});If you may need to remove an interceptor later you can.
varmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);You can add interceptors to a custom instance of axios.
varinstance=axios.create();instance.interceptors.request.use(function(){/*...*/});axios.get('/user/12345').catch(function(response){if(responseinstanceofError){// Something happened in setting up the request that triggered an Errorconsole.log('Error',response.message);}else{// The request was made, but the server responded with a status code// that falls out of the range of 2xxconsole.log(response.data);console.log(response.status);console.log(response.headers);console.log(response.config);}});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.
axios depends on a native ES6 Promise implementation to be supported. If your environment doesn't support ES6 Promises, you can polyfill.
axios includes a TypeScript definition.
/// <reference path="axios.d.ts" />importaxios= require('axios');axios.get('/user?ID=12345');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.
MIT




