π₯ Gold sponsors
API-first authentication, authorization, and fraud prevention |
Weβre bound by one common purpose: to give you the financial tools, resources and information you ne... |
Buy real Instagram followers from Twicsy starting at only $2.97. Twicsy has been voted the best site... |
Hi, we're Descope! We are building something in the authentication space for app developers and... |
Best Route Planning And Route Optimization Software Explore | Free Trial | Contact |
At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rate... |
Buy Instagram Likes |
A lightweight open-source API Development, Testing & Mocking platform |
π Become a sponsor |
Promise based HTTP client for the browser and node.js
Website β’ Documentation
Table of Contents
- Features
- Browser Support
- Installing
- Example
- Axios API
- Request method aliases
- Concurrency π
- Creating an instance
- Instance methods
- Request Config
- Response Schema
- Config Defaults
- Interceptors
- Handling Errors
- Cancellation
- Using application/x-www-form-urlencoded format
- Using multipart/form-data format
- Files Posting
- HTML Form Posting
- π Progress capturing
- π Rate limiting
- π AxiosHeaders
- π₯ Fetch adapter
- π₯ HTTP2
- Semver
- Promises
- TypeScript
- Resources
- Credits
- License
Features
- Browser Requests: Make XMLHttpRequests directly from the browser.
- Node.js Requests: Make http requests from Node.js environments.
- Promise-based: Fully supports the Promise API for easier asynchronous code.
- Interceptors: Intercept requests and responses to add custom logic or transform data.
- Data Transformation: Transform request and response data automatically.
- Request Cancellation: Cancel requests using built-in mechanisms.
- Automatic JSON Handling: Automatically serializes and parses JSON data.
- Form Serialization: π Automatically serializes data objects to
multipart/form-dataorx-www-form-urlencodedformats.
- XSRF Protection: Client-side support to protect against Cross-Site Request Forgery.
Browser Support
| Chrome | Firefox | Safari | Opera | Edge |
|---|---|---|---|---|
![]() |
![]() |
![]() |
![]() |
![]() |
| Latest β | Latest β | Latest β | Latest β | Latest β |
Installing
Package manager
Using npm:
1 | $ npm install axios |
Using bower:
1 | $ bower install axios |
Using yarn:
1 | $ yarn add axios |
Using pnpm:
1 | $ pnpm add axios |
Using bun:
1 | $ bun add axios |
Once the package is installed, you can import the library using import or require approach:
1 | 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:
1 | import axios from 'axios'; |
For some bundlers and some ES6 linters you may need to do the following:
1 | import { default as axios } from 'axios'; |
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:
1 | const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017) |
CDN
Using jsDelivr CDN (ES5 UMD browser module):
1 | <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script> |
Using unpkg CDN:
1 | <script src="https://unpkg.com/[email protected]/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:
1 | import axios from 'axios'; |
Note:
async/awaitis part of ECMAScript 2017 and is not supported in Internet Explorer and older browsers, so use with caution.
Performing a POST request
1 | axios.post('/user', { |
Performing multiple concurrent requests
1 | function getUserAccount() { |
axios API
Requests can be made by passing the relevant config to axios.
axios(config)
1 | // Send a POST request |
1 | // GET request for remote image in node.js |
axios(url[, config])
1 | // Send a GET request (default method) |
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])
1 | const instance = axios.create({ |
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.
1 | { |
Response Schema
The response for a request contains the following information.
1 | { |
When using then, you will receive the response as follows:
1 | axios.get('/user/12345') |
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
1 | axios.defaults.baseURL = 'https://api.example.com'; |
Custom instance defaults
1 | // Set config defaults when creating the instance |
Config order of precedence
Config will be merged with an order of precedence. The order is library defaults found in lib/defaults/index.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.
1 | // Create an instance using the config defaults provided by the library |
Interceptors
You can intercept requests or responses before they are handled by then or catch.
1 |
|
If you need to remove an interceptor later you can.
1 | const instance = axios.create(); |
You can also clear all interceptors for requests or responses. 1
2
3
4
5const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
instance.interceptors.request.clear(); // Removes interceptors from requests
instance.interceptors.response.use(function () {/*...*/});
instance.interceptors.response.clear(); // Removes interceptors from responses
You can add interceptors to a custom instance of axios.
1 | const instance = axios.create(); |
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.
1 | axios.interceptors.request.use(function (config) { |
If you want to execute a particular interceptor based on a runtime check, you can add a runWhen function to the options object. The request 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.
1 | function onGetCall(config) { |
Note: options parameter(having
synchronousandrunWhenproperties) is only supported for request interceptors at the moment.
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.
Error Types
There are many different axios error messages that can appear that can provide basic information about the specifics of the error and where opportunities may lie in debugging.
The general structure of axios errors is as follows: | Property | Definition | | -------- | ---------- | | message | A quick summary of the error message and the status it failed with. | | name | This defines where the error originated from. For axios, it will always be an 'AxiosError'. | | stack | Provides the stack trace of the error. | | config | An axios config object with specific instance configurations defined by the user from when the request was made | | code | Represents an axios identified error. The table below lists out specific definitions for internal axios error. | | status | HTTP response status code. See here for common HTTP response status code meanings.
Below is a list of potential axios identified error:
| Code | Definition |
|---|---|
| ERR_BAD_OPTION_VALUE | Invalid value provided in axios configuration. |
| ERR_BAD_OPTION | Invalid option provided in axios configuration. |
| ERR_NOT_SUPPORT | Feature or method not supported in the current axios environment. |
| ERR_DEPRECATED | Deprecated feature or method used in axios. |
| ERR_INVALID_URL | Invalid URL provided for axios request. |
| ECONNABORTED | Typically indicates that the request has been timed out (unless transitional.clarifyTimeoutError is set) or aborted by the browser or its plugin. |
| ERR_CANCELED | Feature or method is canceled explicitly by the user using an AbortSignal (or a CancelToken). |
| ETIMEDOUT | Request timed out due to exceeding default axios timelimit. transitional.clarifyTimeoutError must be set to true, otherwise a generic ECONNABORTED error will be thrown instead. |
| ERR_NETWORK | Network-related issue. In the browser, this error can also be caused by a CORS or Mixed Content policy violation. The browser does not allow the JS code to clarify the real reason for the error caused by security issues, so please check the console. |
| ERR_FR_TOO_MANY_REDIRECTS | Request is redirected too many times; exceeds max redirects specified in axios configuration. |
| ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. Usually related to a response with 5xx status code. |
| ERR_BAD_REQUEST | The request has an unexpected format or is missing required parameters. Usually related to a response with 4xx status 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.
1 | axios.get('/user/12345') |
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.
1 | axios.get('/user/12345', { |
Using toJSON you get an object with more information about the HTTP error.
1 | axios.get('/user/12345') |
Cancellation
AbortController
Starting from v0.22.0 Axios supports AbortController to cancel requests in fetch API way:
1 | const controller = new AbortController(); |
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:
1 | const CancelToken = axios.CancelToken; |
You can also create a cancel token by passing an executor function to the CancelToken constructor:
1 | const CancelToken = axios.CancelToken; |
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).
1 | const params = new URLSearchParams({ foo: 'bar' }); |
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:
1 | const qs = require('qs'); |
Or in another way (ES6),
1 | import qs from 'qs'; |
Older Node.js versions
For older Node.js engines, you can use the querystring module as follows:
1 | const querystring = require('querystring'); |
You can also use the qs library.
Note: The
qslibrary is preferable if you need to stringify nested objects, as thequerystringmethod 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".
1 | const data = { |
The server will handle it as:
1 | { |
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.
1 | const formData = new FormData(); |
In node.js, you can use the form-data library as follows:
1 | const FormData = require('form-data'); |
π 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):
1 | import axios from 'axios'; |
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:
1 | const axios = require('axios'); |
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 aFormDataobject 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.guser{}: '{"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 offlatarray-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:
1 | const obj = { |
The following steps will be executed by the Axios serializer internally:
1 | const formData = new FormData(); |
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:
1 | await axios.postForm('https://httpbin.org/post', { |
or multiple files as multipart/form-data:
1 | await axios.postForm('https://httpbin.org/post', { |
FileList object can be passed directly:
1 | 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.
1 | 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:
1 | await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), { |
For example, the Form
1 | <form id="form"> |
will be submitted as the following JSON object:
1 | { |
You can also track stream upload/download progress in node.js:
1 | const {data} = await axios.post(SERVER_URL, readableStream, { |
π AxiosHeaders
Axios has its own AxiosHeaders class to manipulate headers using a Map-like API that guarantees caseless work. Although HTTP is case-insensitive in headers, Axios will retain the case of the original header for stylistic reasons and for a workaround when servers mistakenly consider the header's case. The old approach of directly manipulating headers object is still available, but deprecated and not recommended for future usage.
Working with headers
An AxiosHeaders object instance can contain different types of internal values. that control setting and merging logic. The final headers object with string values is obtained by Axios by calling the toJSON method.
Note: By JSON here we mean an object consisting only of string values intended to be sent over the network.
The header value can be one of the following types: - string - normal string value that will be sent to the server - null - skip header when rendering to JSON - false - skip header when rendering to JSON, additionally indicates that set method must be called with rewrite option set to true to overwrite this value (Axios uses this internally to allow users to opt out of installing certain headers like User-Agent or Content-Type) - undefined - value is not set
Note: The header value is considered set if it is not equal to undefined.
The headers object is always initialized inside interceptors and transformers:
1 | axios.interceptors.request.use((request: InternalAxiosRequestConfig) => { |
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
If the headers object is a string, it will be parsed as RAW HTTP headers.
````js
const headers = new AxiosHeaders(`
Host: www.bing.com
User-Agent: curl/7.54.0
Accept: */*`);
console.log(headers);
// Object [AxiosHeaders] {
// host: 'www.bing.com',
// 'user-agent': 'curl/7.54.0',
// accept: '*/*'
// }
````
### AxiosHeaders#set
```ts
set(headerName, value: Axios, rewrite?: boolean);
set(headerName, value, rewrite?: (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean);
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean);
The rewrite argument controls the overwriting behavior: - false - do not overwrite if header's value is set (is not undefined) - undefined (default) - overwrite the header unless its value is set to false - true - rewrite anyway
The option can also accept a user-defined function that determines whether the value should be overwritten or not.
Returns this.
AxiosHeaders#get(header)
1 | get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue; |
Returns the value of the header.
AxiosHeaders#has(header, matcher?)
1 | has(header: string, matcher?: AxiosHeaderMatcher): boolean; |
Returns true if the header is set (has no undefined value).
AxiosHeaders#delete(header, matcher?)
1 | delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; |
Returns true if at least one header has been removed.
AxiosHeaders#clear(matcher?)
1 | clear(matcher?: AxiosHeaderMatcher): boolean; |
Removes all headers. Unlike the delete method matcher, this optional matcher will be used to match against the header name rather than the value.
1 | const headers = new AxiosHeaders({ |
Returns true if at least one header has been cleared.
AxiosHeaders#normalize(format);
If the headers object was changed directly, it can have duplicates with the same name but in different cases. This method normalizes the headers object by combining duplicate keys into one. Axios uses this method internally after calling each interceptor. Set format to true for converting headers name to lowercase and capitalize the initial letters (cOntEnt-type => Content-Type)
1 | const headers = new AxiosHeaders({ |
Returns this.
AxiosHeaders#concat(...targets)
1 | concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders; |
Merges the instance with targets into a new AxiosHeaders instance. If the target is a string, it will be parsed as RAW HTTP headers.
Returns a new AxiosHeaders instance.
AxiosHeaders#toJSON(asStrings?)
1 | toJSON(asStrings?: boolean): RawAxiosHeaders; |
Resolve all internal headers values into a new null prototype object. Set asStrings to true to resolve arrays as a string containing all elements, separated by commas.
AxiosHeaders.from(thing?)
1 | from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; |
Returns a new AxiosHeaders instance created from the raw headers passed in, or simply returns the given headers object if it's an AxiosHeaders instance.
AxiosHeaders.concat(...targets)
1 | concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders; |
Returns a new AxiosHeaders instance created by merging the target objects.
Shortcuts
The following shortcuts are available:
setContentType,getContentType,hasContentTypesetContentLength,getContentLength,hasContentLengthsetAccept,getAccept,hasAcceptsetUserAgent,getUserAgent,hasUserAgentsetContentEncoding,getContentEncoding,hasContentEncoding
π₯ Fetch adapter
Fetch adapter was introduced in v1.7.0. By default, it will be used if xhr and http adapters are not available in the build, or not supported by the environment. To use it by default, it must be selected explicitly:
1 | const {data} = axios.get(url, { |
You can create a separate instance for this:
1 | const fetchAxios = axios.create({ |
The adapter supports the same functionality as xhr adapter, including upload and download progress capturing. Also, it supports additional response types such as stream and formdata (if supported by the environment).
π₯ Custom fetch
Starting from v1.12.0, you can customize the fetch adapter to use a custom fetch API instead of environment globals. You can pass a custom fetch function, Request, and Response constructors via env config. This can be helpful in case of custom environments & app frameworks.
Also, when using a custom fetch, you may need to set custom Request and Response too. If you don't set them, global objects will be used. If your custom fetch api does not have these objects, and the globals are incompatible with a custom fetch, you must disable their use inside the fetch adapter by passing null.
Note: Setting
Request&Responsetonullwill make it impossible for the fetch adapter to capture the upload & download progress.
Basic example:
1 | import customFetchFunction from 'customFetchModule'; |
π₯ Using with Tauri
A minimal example of setting up Axios for use in a Tauri app with a platform fetch function that ignores CORS policy for requests.
1 | import { fetch } from "@tauri-apps/plugin-http"; |
π₯ Using with SvelteKit
SvelteKit framework has a custom implementation of the fetch function for server rendering (so called load functions), and also uses relative paths, which makes it incompatible with the standard URL API. So, Axios must be configured to use the custom fetch API:
1 | export async function load({ fetch }) { |
π₯ HTTP2
In version 1.13.0, experimental HTTP2 support was added to the http adapter. The httpVersion option is now available to select the protocol version used. Additional native options for the internal session.request() call can be passed via the http2Options config. This config also includes the custom sessionTimeout parameter, which defaults to 1000ms.
1 | const form = new FormData(); |
Semver
Since Axios has reached a v.1.0.0 we will fully embrace semver as per the spec here
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.
1 | let user: User = null; |
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.




