axios

๐Ÿฅ‡ Gold sponsors

Stytch

API-first authentication, authorization, and fraud prevention

Website | Documentation | Node.js

Principal Financial Group

Weโ€™re bound by one common purpose: to give you the financial tools, resources and information you ne...

www.principal.com

Buy Instagram Followers Twicsy

Buy real Instagram followers from Twicsy starting at only $2.97. Twicsy has been voted the best site...

twicsy.com

Descope

Hi, we're Descope! We are building something in the authentication space for app developers and...

Website | Docs | Community

Route4Me

Best Route Planning And Route Optimization Software

Explore | Free Trial | Contact

Buzzoid - Buy Instagram Followers

At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rate...

buzzoid.com

Famety - Buy Instagram Followers

At Famety, you can grow your social media following quickly, safely, and easily with just a few clic...

www.famety.net

Poprey - Buy Instagram Likes

Buy Instagram Likes

poprey.com

Requestly

A lightweight open-source API Development, Testing & Mocking platform

requestly.com

Axios

Promise based HTTP client for the browser and node.js

Website โ€ข Documentation

npm version CDNJS Build status Gitpod Ready-to-Code code coverage install size npm bundle size npm downloads gitter chat code helpers Known Vulnerabilities Contributors

Table of Contents

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-data or x-www-form-urlencoded formats.

  • XSRF Protection: Client-side support to protect against Cross-Site Request Forgery.

Browser Support

Chrome
Firefox
Safari
Opera
Edge

Chrome browser logo

Firefox browser logo

Safari browser logo

Opera browser logo

Edge browser logo

Latest โœ”

Latest โœ”

Latest โœ”

Latest โœ”

Latest โœ”

Browser Matrix

Installing

Package manager

Using npm:

Using bower:

Using yarn:

Using pnpm:

Using bun:

Once the package is installed, you can import the library using import or require approach:

You can also use the default export, since the named export is just a re-export from the Axios factory:

If you use require for importing, only default export is available:

For some bundlers and some ES6 linters you may need to do the following:

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:

CDN

Using jsDelivr CDN (ES5 UMD browser module):

Using unpkg CDN:

Example

Note: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with require(), use the following approach:

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

Performing multiple concurrent requests

axios API

Requests can be made by passing the relevant config to axios.

axios(config)

axios(url[, config])

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])

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.

Response Schema

The response for a request contains the following information.

When using then, you will receive the response as follows:

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

Custom instance defaults

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.

Interceptors

You can intercept requests or responses before they are handled by then or catch.

If you need to remove an interceptor later you can.

You can also clear all interceptors for requests or responses.

You can add interceptors to a custom instance of axios.

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.

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.

Note: options parameter(having synchronous and runWhen properties) 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.

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.

Using toJSON you get an object with more information about the HTTP error.

Cancellation

AbortController

Starting from v0.22.0 Axios supports AbortController to cancel requests in fetch API way:

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:

You can also create a cancel token by passing an executor function to the CancelToken constructor:

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).

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:

Or in another way (ES6),

Older Node.js versions

For older Node.js engines, you can use the querystring module as follows:

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".

The server will handle it as:

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

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.

In node.js, you can use the form-data library as follows:

๐Ÿ†• 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):

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:

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:

The following steps will be executed by the Axios serializer internally:

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:

or multiple files as multipart/form-data:

FileList object can be passed directly:

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.

FormData and HTMLForm objects can also be posted as JSON by explicitly setting the Content-Type header to application/json:

For example, the Form

will be submitted as the following JSON object:

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. The frequency of progress events is forced to be limited to 3 times per second.

You can also track stream upload/download progress in node.js:

Note: Capturing FormData upload progress is 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):

๐Ÿ†• 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:

You can iterate over an AxiosHeaders instance using a for...of statement:

new AxiosHeaders(headers?)

Constructs a new AxiosHeaders instance.

If the headers object is a string, it will be parsed as RAW HTTP headers.

AxiosHeaders#set

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)

Returns the internal value of the header. It can take an extra argument to parse the header's value with RegExp.exec, matcher function or internal key-value parser.

Returns the value of the header.

AxiosHeaders#has(header, matcher?)

Returns true if the header is set (has no undefined value).

AxiosHeaders#delete(header, matcher?)

Returns true if at least one header has been removed.

AxiosHeaders#clear(matcher?)

Removes all headers. Unlike the delete method matcher, this optional matcher will be used to match against the header name rather than the value.

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)

Returns this.

AxiosHeaders#concat(...targets)

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?)

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?)

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)

Returns a new AxiosHeaders instance created by merging the target objects.

Shortcuts

The following shortcuts are available:

  • setContentType, getContentType, hasContentType

  • setContentLength, getContentLength, hasContentLength

  • setAccept, getAccept, hasAccept

  • setUserAgent, getUserAgent, hasUserAgent

  • setContentEncoding, 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:

You can create a separate instance for this:

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 & Response to null will make it impossible for the fetch adapter to capture the upload & download progress.

Basic example:

๐Ÿ”ฅ 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.

๐Ÿ”ฅ 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:

๐Ÿ”ฅ 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.

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.

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.

Open in Gitpod

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

License: MIT

Last updated