Promise based HTTP client for the browser and node.js
Website โข
Documentation
Table of Contents
Features
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Automatic transforms for JSON data
- ๐ Automatic data object serialization to
multipart/form-data
and x-www-form-urlencoded
body encodings - Client side support for protecting against XSRF
Browser Support
| | | | | |
---|
Latest โ | Latest โ | Latest โ | Latest โ | Latest โ | 11 โ |
Installing
Package manager
Using npm:
$ npm install axios
Using bower:
$ bower install axios
Using yarn:
$ yarn add axios
Using pnpm:
$ pnpm add axios
Once the package is installed, you can import the library using import
or require
approach:
import axios, {isCancel, AxiosError} from 'axios';
You can also use the default export, since the named export is just a re-export from the Axios factory:
import axios from 'axios';
console.log(axios.isCancel('something'));
If you use require
for importing, only default export is available:
const axios = require('axios');
console.log(axios.isCancel('something'));
For cases where something went wrong when trying to import a module into a custom or legacy environment,
you can try importing the module package directly:
const axios = require('axios/dist/browser/axios.cjs');
CDN
Using jsDelivr CDN (ES5 UMD browser module):
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
Using unpkg CDN:
<script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
Example
Note CommonJS usage
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with require()
, use the following approach:
import axios from 'axios';
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
Note async/await
is part of ECMAScript 2017 and is not supported in Internet
Explorer and older browsers, so use with caution.
Performing a POST
request
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Performing multiple concurrent requests
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});
axios API
Requests can be made by passing the relevant config to axios
.
axios(config)
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios({
method: 'get',
url: 'https://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
axios(url[, config])
axios('/user/12345');
Request method aliases
For convenience, aliases have been provided for all common 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]])
NOTE
When using the alias methods url
, method
, and data
properties don't need to be specified in config.
Concurrency (Deprecated)
Please use Promise.all
to replace the below functions.
Helper functions for dealing with concurrent requests.
axios.all(iterable)
axios.spread(callback)
Creating an instance
You can create a new instance of axios with a custom config.
axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
Instance methods
The available instance methods are listed below. The specified config will be merged with the instance config.
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]])
axios#getUri([config])
Request 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: '/user',
method: 'get',
baseURL: 'https://some-domain.com/api/',
transformRequest: [function (data, headers) {
return data;
}],
transformResponse: [function (data) {
return data;
}],
headers: {'X-Requested-With': 'XMLHttpRequest'},
params: {
ID: 12345
},
paramsSerializer: {
encode?: (param: string): string => { },
serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),
indexes: false
},
data: {
firstName: 'Fred'
},
data: 'Country=Brasil&City=Belo Horizonte',
timeout: 1000,
withCredentials: false,
adapter: function (config) {
},
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
responseType: 'json',
responseEncoding: 'utf8',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
},
onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
},
maxContentLength: 2000,
maxBodyLength: 2000,
validateStatus: function (status) {
return status >= 200 && status < 300;
},
maxRedirects: 21,
beforeRedirect: (options, { headers }) => {
if (options.hostname === "example.com") {
options.auth = "user:password";
}
},
socketPath: null,
transport: undefined,
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
cancelToken: new CancelToken(function (cancel) {
}),
signal: new AbortController().signal,
decompress: true
insecureHTTPParser: undefined
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false,
},
env: {
FormData: window?.FormData || global?.FormData
},
formSerializer: {
visitor: (value, key, path, helpers) => {};
dots: boolean;
metaTokens: boolean;
indexes: boolean;
},
maxRate: [
100 * 1024,
100 * 1024
]
}
Response Schema
The response for a request contains the following information.
{
data: {},
status: 200,
statusText: 'OK',
headers: {},
config: {},
request: {}
}
When using then
, 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);
});
When using catch
, or passing a rejection callback as second parameter of then
, the response will be available through the error
object as explained in the Handling Errors section.
Config Defaults
You can specify config defaults that will be applied to every request.
Global axios defaults
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
const instance = axios.create({
baseURL: 'https://api.example.com'
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Config order of precedence
Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults
property of the instance, and finally config
argument for the request. The latter will take precedence over the former. Here's an example.
const instance = axios.create();
instance.defaults.timeout = 2500;
instance.get('/longRequest', {
timeout: 5000
});
Interceptors
You can intercept requests or responses before they are handled by then
or catch
.
axios.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
return Promise.reject(error);
});
If you need to remove an interceptor later you can.
const myInterceptor = axios.interceptors.request.use(function () {});
axios.interceptors.request.eject(myInterceptor);
You can also clear all interceptors for requests or responses.
const instance = axios.create();
instance.interceptors.request.use(function () {});
instance.interceptors.request.clear();
instance.interceptors.response.use(function () {});
instance.interceptors.response.clear();
You can add interceptors to a custom instance of axios.
const instance = axios.create();
instance.interceptors.request.use(function () {});
When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag
to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
axios.interceptors.request.use(function (config) {
config.headers.test = 'I am only a header!';
return config;
}, null, { synchronous: true });
If you want to execute a particular interceptor based on a runtime check,
you can add a runWhen
function to the options object. The interceptor will not be executed if and only if the return
of runWhen
is false
. The function will be called with the config
object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
asynchronous request interceptor that only needs to run at certain times.
function onGetCall(config) {
return config.method === 'get';
}
axios.interceptors.request.use(function (config) {
config.headers.test = 'special get headers';
return config;
}, null, { runWhen: onGetCall });
Multiple Interceptors
Given you add multiple response interceptors
and when the response was fulfilled
- then each interceptor is executed
- then they are executed in the order they were added
- then only the last interceptor's result is returned
- then every interceptor receives the result of its predecessor
- and when the fulfillment-interceptor throws
- then the following fulfillment-interceptor is not called
- then the following rejection-interceptor is called
- once caught, another following fulfill-interceptor is called again (just like in a promise chain).
Read the interceptor tests for seeing all this in code.
Handling Errors
the default behavior is to reject every response that returns with a status code that falls out of the range of 2xx and treat it as an error.
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
});
Using the validateStatus
config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error.
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500;
}
})
Using toJSON
you get an object with more information about the HTTP error.
axios.get('/user/12345')
.catch(function (error) {
console.log(error.toJSON());
});
Cancellation
AbortController
Starting from v0.22.0
Axios supports AbortController to cancel requests in fetch API way:
const controller = new AbortController();
axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
});
controller.abort()
CancelToken ๐deprecated
You can also cancel a request using a CancelToken.
The axios cancel token API is based on the withdrawn cancellable promises proposal.
This API is deprecated since v0.22.0 and shouldn't be used in new projects
You can create a cancel token using the CancelToken.source
factory as shown below:
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 {
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
source.cancel('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the CancelToken
constructor:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
});
cancel();
Note: you can cancel several requests with the same cancel token/abort controller.
If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make a real request.
During the transition period, you can use both cancellation APIs, even for the same request:
Using application/x-www-form-urlencoded
format
URLSearchParams
By default, axios serializes JavaScript objects to JSON
. To send data in the application/x-www-form-urlencoded
format instead, you can use the URLSearchParams
API, which is supported in the vast majority of browsers,and Node starting with v10 (released in 2018).
const params = new URLSearchParams({ foo: 'bar' });
params.append('extraparam', 'value');
axios.post('/foo', params);
Query string (Older browsers)
For compatibility with very old browsers, there is a polyfill available (make sure to polyfill the global environment).
Alternatively, you can encode data using the qs
library:
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);
Older Node.js versions
For older Node.js engines, you can use the querystring
module as follows:
const querystring = require('querystring');
axios.post('https://something.com/', querystring.stringify({ foo: 'bar' }));
You can also use the qs
library.
Note
The qs
library is preferable if you need to stringify nested objects, as the querystring
method has known issues with that use case.
๐ Automatic serialization to URLSearchParams
Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".
const data = {
x: 1,
arr: [1, 2, 3],
arr2: [1, [2], 3],
users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
};
await axios.postForm('https://postman-echo.com/post', data,
{headers: {'content-type': 'application/x-www-form-urlencoded'}}
);
The server will handle it as:
{
x: '1',
'arr[]': [ '1', '2', '3' ],
'arr2[0]': '1',
'arr2[1][0]': '2',
'arr2[2]': '3',
'arr3[]': [ '1', '2', '3' ],
'users[0][name]': 'Peter',
'users[0][surname]': 'griffin',
'users[1][name]': 'Thomas',
'users[1][surname]': 'Anderson'
}
If your backend body-parser (like body-parser
of express.js
) supports nested objects decoding, you will get the same object on the server-side automatically
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function (req, res, next) {
res.send(JSON.stringify(req.body));
});
server = app.listen(3000);
Using multipart/form-data
format
FormData
To send the data as a multipart/formdata
you need to pass a formData instance as a payload.
Setting the Content-Type
header is not required as Axios guesses it based on the payload type.
const formData = new FormData();
formData.append('foo', 'bar');
axios.post('https://httpbin.org/post', formData);
In node.js, you can use the form-data
library as follows:
const FormData = require('form-data');
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
axios.post('https://example.com', form)
๐ Automatic serialization to FormData
Starting from v0.27.0
, Axios supports automatic object serialization to a FormData object if the request Content-Type
header is set to multipart/form-data
.
The following request will submit the data in a FormData format (Browser & Node.js):
import axios from 'axios';
axios.post('https://httpbin.org/post', {x: 1}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(({data}) => console.log(data));
In the node.js
build, the (form-data
) polyfill is used by default.
You can overload the FormData class by setting the env.FormData
config variable,
but you probably won't need it in most cases:
const axios = require('axios');
var FormData = require('form-data');
axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(({data}) => console.log(data));
Axios FormData serializer supports some special endings to perform the following operations:
{}
- serialize the value with JSON.stringify[]
- unwrap the array-like object as separate fields with the same key
Note
unwrap/expand operation will be used by default on arrays and FileList objects
FormData serializer supports additional options via config.formSerializer: object
property to handle rare cases:
-
visitor: Function
- user-defined visitor function that will be called recursively to serialize the data object
to a FormData
object by following custom rules.
-
dots: boolean = false
- use dot notation instead of brackets to serialize arrays and objects;
-
metaTokens: boolean = true
- add the special ending (e.g user{}: '{"name": "John"}'
) in the FormData key.
The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON.
-
indexes: null|false|true = false
- controls how indexes will be added to unwrapped keys of flat
array-like objects
null
- don't add brackets (arr: 1
, arr: 2
, arr: 3
)false
(default) - add empty brackets (arr[]: 1
, arr[]: 2
, arr[]: 3
)true
- add brackets with indexes (arr[0]: 1
, arr[1]: 2
, arr[2]: 3
)
Let's say we have an object like this one:
const obj = {
x: 1,
arr: [1, 2, 3],
arr2: [1, [2], 3],
users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
'obj2{}': [{x:1}]
};
The following steps will be executed by the Axios serializer internally:
const formData = new FormData();
formData.append('x', '1');
formData.append('arr[]', '1');
formData.append('arr[]', '2');
formData.append('arr[]', '3');
formData.append('arr2[0]', '1');
formData.append('arr2[1][0]', '2');
formData.append('arr2[2]', '3');
formData.append('users[0][name]', 'Peter');
formData.append('users[0][surname]', 'Griffin');
formData.append('users[1][name]', 'Thomas');
formData.append('users[1][surname]', 'Anderson');
formData.append('obj2{}', '[{"x":1}]');
Axios supports the following shortcut methods: postForm
, putForm
, patchForm
which are just the corresponding http methods with the Content-Type
header preset to multipart/form-data
.
Files Posting
You can easily submit a single file:
await axios.postForm('https://httpbin.org/post', {
'myVar' : 'foo',
'file': document.querySelector('#fileInput').files[0]
});
or multiple files as multipart/form-data
:
await axios.postForm('https://httpbin.org/post', {
'files[]': document.querySelector('#fileInput').files
});
FileList
object can be passed directly:
await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
All files will be sent with the same field names: files[]
.
๐ HTML Form Posting (browser)
Pass HTML Form element as a payload to submit it as multipart/form-data
content.
await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
FormData
and HTMLForm
objects can also be posted as JSON
by explicitly setting the Content-Type
header to application/json
:
await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
headers: {
'Content-Type': 'application/json'
}
})
For example, the Form
<form id="form">
<input type="text" name="foo" value="1">
<input type="text" name="deep.prop" value="2">
<input type="text" name="deep prop spaced" value="3">
<input type="text" name="baz" value="4">
<input type="text" name="baz" value="5">
<select name="user.age">
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
<input type="submit" value="Save">
</form>
will be submitted as the following JSON object:
{
"foo": "1",
"deep": {
"prop": {
"spaced": "3"
}
},
"baz": [
"4",
"5"
],
"user": {
"age": "value2"
}
}
Sending Blobs
/Files
as JSON (base64
) is not currently supported.
๐ Progress capturing
Axios supports both browser and node environments to capture request upload/download progress.
await axios.post(url, data, {
onUploadProgress: function (axiosProgressEvent) {
},
onDownloadProgress: function (axiosProgressEvent) {
}
});
You can also track stream upload/download progress in node.js:
const {data} = await axios.post(SERVER_URL, readableStream, {
onUploadProgress: ({progress}) => {
console.log((progress * 100).toFixed(2));
},
headers: {
'Content-Length': contentLength
},
maxRedirects: 0
});
Note:
Capturing FormData upload progress is currently not currently supported in node.js environments.
โ ๏ธ Warning
It is recommended to disable redirects by setting maxRedirects: 0 to upload the stream in the node.js environment,
as follow-redirects package will buffer the entire stream in RAM without following the "backpressure" algorithm.
๐ Rate limiting
Download and upload rate limits can only be set for the http adapter (node.js):
const {data} = await axios.post(LOCAL_SERVER_URL, myBuffer, {
onUploadProgress: ({progress, rate}) => {
console.log(`Upload [${(progress*100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`)
},
maxRate: [100 * 1024],
});
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 depends on a native ES6 Promise implementation to be supported.
If your environment doesn't support ES6 Promises, you can polyfill.
TypeScript
axios includes TypeScript definitions and a type guard for axios errors.
let user: User = null;
try {
const { data } = await axios.get('/user?ID=12345');
user = data.userDetails;
} catch (error) {
if (axios.isAxiosError(error)) {
handleAxiosError(error);
} else {
handleUnexpectedError(error);
}
}
Because axios dual publishes with an ESM default export and a CJS module.exports
, there are some caveats.
The recommended setting is to use "moduleResolution": "node16"
(this is implied by "module": "node16"
). Note that this requires TypeScript 4.7 or greater.
If use ESM, your settings should be fine.
If you compile TypeScript to CJS and you canโt use "moduleResolution": "node 16"
, you have to enable esModuleInterop
.
If you use TypeScript to type check CJS JavaScript code, your only option is to use "moduleResolution": "node16"
.
Online one-click setup
You can use Gitpod, an online IDE(which is free for Open Source) for contributing or running the examples online.
Resources
Credits
axios is heavily inspired by the $http service provided in AngularJS. Ultimately axios is an effort to provide a standalone $http
-like service for use outside of AngularJS.
License
MIT