axios
Promise based XHR library
Features
- Making XMLHttpRequests supporting the Promise API
- Transforming request and response data
- Client side support for protecting against XSRF
- Specifying HTTP request headers
- Automatic transforms for JSON data
Installing
Using bower:
$ bower install axios
Using npm:
$ npm install axios
Compatability
Tested to work with >=IE8, Chrome, Firefox, Safari, and Opera.
Example
Performing a GET
request
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
Performing a POST
request
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
Aliases are provided for success and error
axios.get('/user/12345')
.success(function () {
console.log('user found');
})
.error(function () {
console.log('error finding user');
});
Request API
Requests can be made by passing the relevant config to axios
.
axios(config)
axios({
method: 'get',
url: '/user/12345'
});
Request method aliases
For convenience aliases have been provided for all supported request methods.
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 methods url
, method
, and data
properties don't need to be specified in config.
Config
This is the available config options for making requests. Only the url
is required. Requests will default to GET
if method
is not specified.
{
url: '/user',
method: 'get',
transformRequest: [function (data) {
return data;
}],
transformResponse: [function (data) {
return data;
}],
headers: {'X-Requested-With': 'XMLHttpRequest'},
params: {
ID: 12345
},
data: {
firstName: 'Fred'
},
withCredentials: false,
responseType: 'json',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
}
Response API
For either success
or error
, the following response will be provided.
axios.get('/user/12345')
.success(function (
data,
status,
headers,
config
) {
});
}
Thanks
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.
axios uses the es6-promise polyfill by Jake Archibald. Until we can use ES6 Promises natively in all browsers, this polyfill is a life saver.
License
MIT