Gathering detailed insights and metrics for axios
Gathering detailed insights and metrics for axios
Gathering detailed insights and metrics for axios
Gathering detailed insights and metrics for axios
vue-axios
A small wrapper for integrating axios to Vuejs
axios-retry
Axios plugin that intercepts failed requests and retries them whenever posible.
@types/axios
Stub TypeScript definitions entry for axios, which provides its own types definitions
axios-mock-adapter
Axios adapter that allows to easily mock requests
Promise based HTTP client for the browser and node.js
npm install axios
Typescript
Module System
Node Version
NPM Version
62.7
Supply Chain
99.6
Quality
93.7
Maintenance
100
Vulnerability
100
License
Updated on 05 Dec 2024
Minified
Minified + Gzipped
JavaScript (87.79%)
TypeScript (10.29%)
HTML (1.71%)
Handlebars (0.21%)
Cumulative downloads
Total Downloads
Last day
9.5%
Compared to previous day
Last week
-7.8%
Compared to previous week
Last month
6.2%
Compared to previous month
Last year
14.2%
Compared to previous year
3
57
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... | Hi, we're Descope! We are building something in the authentication space for app developers and... |
At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rate... | At Famety, you can grow your social media following quickly, safely, and easily with just a few clic... | Buy Instagram Likes |
💜 Become a sponsor | 💜 Become a sponsor | 💜 Become a sponsor |
Promise based HTTP client for the browser and node.js
multipart/form-data
and x-www-form-urlencoded
body encodingsLatest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
Using npm:
1$ npm install axios
Using bower:
1$ bower install axios
Using yarn:
1$ yarn add axios
Using pnpm:
1$ pnpm add axios
Once the package is installed, you can import the library using import
or require
approach:
1import 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:
1import axios from 'axios'; 2 3console.log(axios.isCancel('something'));
If you use require
for importing, only default export is available:
1const axios = require('axios'); 2 3console.log(axios.isCancel('something'));
For some bundlers and some ES6 linter's you may need to do the following:
1import { 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:
1const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017) 2// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
Using jsDelivr CDN (ES5 UMD browser module):
1<script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
Using unpkg CDN:
1<script src="https://unpkg.com/axios@1.6.7/dist/axios.min.js"></script>
Note: CommonJS usage
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports withrequire()
, use the following approach:
1import axios from 'axios'; 2//const axios = require('axios'); // legacy way 3 4// Make a request for a user with a given ID 5axios.get('/user?ID=12345') 6 .then(function (response) { 7 // handle success 8 console.log(response); 9 }) 10 .catch(function (error) { 11 // handle error 12 console.log(error); 13 }) 14 .finally(function () { 15 // always executed 16 }); 17 18// Optionally the request above could also be done as 19axios.get('/user', { 20 params: { 21 ID: 12345 22 } 23 }) 24 .then(function (response) { 25 console.log(response); 26 }) 27 .catch(function (error) { 28 console.log(error); 29 }) 30 .finally(function () { 31 // always executed 32 }); 33 34// Want to use async/await? Add the `async` keyword to your outer function/method. 35async function getUser() { 36 try { 37 const response = await axios.get('/user?ID=12345'); 38 console.log(response); 39 } catch (error) { 40 console.error(error); 41 } 42}
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
1axios.post('/user', { 2 firstName: 'Fred', 3 lastName: 'Flintstone' 4 }) 5 .then(function (response) { 6 console.log(response); 7 }) 8 .catch(function (error) { 9 console.log(error); 10 });
Performing multiple concurrent requests
1function getUserAccount() { 2 return axios.get('/user/12345'); 3} 4 5function getUserPermissions() { 6 return axios.get('/user/12345/permissions'); 7} 8 9Promise.all([getUserAccount(), getUserPermissions()]) 10 .then(function (results) { 11 const acct = results[0]; 12 const perm = results[1]; 13 });
Requests can be made by passing the relevant config to axios
.
1// Send a POST request 2axios({ 3 method: 'post', 4 url: '/user/12345', 5 data: { 6 firstName: 'Fred', 7 lastName: 'Flintstone' 8 } 9});
1// GET request for remote image in node.js 2axios({ 3 method: 'get', 4 url: 'https://bit.ly/2mTM3nY', 5 responseType: 'stream' 6}) 7 .then(function (response) { 8 response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 9 });
1// Send a GET request (default method) 2axios('/user/12345');
For convenience, aliases have been provided for all common request methods.
When using the alias methods url
, method
, and data
properties don't need to be specified in config.
Please use Promise.all
to replace the below functions.
Helper functions for dealing with concurrent requests.
axios.all(iterable) axios.spread(callback)
You can create a new instance of axios with a custom config.
1const instance = axios.create({ 2 baseURL: 'https://some-domain.com/api/', 3 timeout: 1000, 4 headers: {'X-Custom-Header': 'foobar'} 5});
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.
1{ 2 // `url` is the server URL that will be used for the request 3 url: '/user', 4 5 // `method` is the request method to be used when making the request 6 method: 'get', // default 7 8 // `baseURL` will be prepended to `url` unless `url` is absolute. 9 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs 10 // to methods of that instance. 11 baseURL: 'https://some-domain.com/api/', 12 13 // `transformRequest` allows changes to the request data before it is sent to the server 14 // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' 15 // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, 16 // FormData or Stream 17 // You may modify the headers object. 18 transformRequest: [function (data, headers) { 19 // Do whatever you want to transform the data 20 21 return data; 22 }], 23 24 // `transformResponse` allows changes to the response data to be made before 25 // it is passed to then/catch 26 transformResponse: [function (data) { 27 // Do whatever you want to transform the data 28 29 return data; 30 }], 31 32 // `headers` are custom headers to be sent 33 headers: {'X-Requested-With': 'XMLHttpRequest'}, 34 35 // `params` are the URL parameters to be sent with the request 36 // Must be a plain object or a URLSearchParams object 37 params: { 38 ID: 12345 39 }, 40 41 // `paramsSerializer` is an optional config that allows you to customize serializing `params`. 42 paramsSerializer: { 43 44 //Custom encoder function which sends key/value pairs in an iterative fashion. 45 encode?: (param: string): string => { /* Do custom operations here and return transformed string */ }, 46 47 // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour. 48 serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), 49 50 //Configuration for formatting array indexes in the params. 51 indexes: false // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes). 52 }, 53 54 // `data` is the data to be sent as the request body 55 // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH' 56 // When no `transformRequest` is set, must be of one of the following types: 57 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams 58 // - Browser only: FormData, File, Blob 59 // - Node only: Stream, Buffer, FormData (form-data package) 60 data: { 61 firstName: 'Fred' 62 }, 63 64 // syntax alternative to send data into the body 65 // method post 66 // only the value is sent, not the key 67 data: 'Country=Brasil&City=Belo Horizonte', 68 69 // `timeout` specifies the number of milliseconds before the request times out. 70 // If the request takes longer than `timeout`, the request will be aborted. 71 timeout: 1000, // default is `0` (no timeout) 72 73 // `withCredentials` indicates whether or not cross-site Access-Control requests 74 // should be made using credentials 75 withCredentials: false, // default 76 77 // `adapter` allows custom handling of requests which makes testing easier. 78 // Return a promise and supply a valid response (see lib/adapters/README.md) 79 adapter: function (config) { 80 /* ... */ 81 }, 82 // Also, you can set the name of the built-in adapter, or provide an array with their names 83 // to choose the first available in the environment 84 adapter: 'xhr' // 'fetch' | 'http' | ['xhr', 'http', 'fetch'] 85 86 // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. 87 // This will set an `Authorization` header, overwriting any existing 88 // `Authorization` custom headers you have set using `headers`. 89 // Please note that only HTTP Basic auth is configurable through this parameter. 90 // For Bearer tokens and such, use `Authorization` custom headers instead. 91 auth: { 92 username: 'janedoe', 93 password: 's00pers3cret' 94 }, 95 96 // `responseType` indicates the type of data that the server will respond with 97 // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' 98 // browser only: 'blob' 99 responseType: 'json', // default 100 101 // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) 102 // Note: Ignored for `responseType` of 'stream' or client-side requests 103 // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url', 104 // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8', 105 // 'utf8', 'UTF8', 'utf16le', 'UTF16LE' 106 responseEncoding: 'utf8', // default 107 108 // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token 109 xsrfCookieName: 'XSRF-TOKEN', // default 110 111 // `xsrfHeaderName` is the name of the http header that carries the xsrf token value 112 xsrfHeaderName: 'X-XSRF-TOKEN', // default 113 114 // `undefined` (default) - set XSRF header only for the same origin requests 115 withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined), 116 117 // `onUploadProgress` allows handling of progress events for uploads 118 // browser & node.js 119 onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) { 120 // Do whatever you want with the Axios progress event 121 }, 122 123 // `onDownloadProgress` allows handling of progress events for downloads 124 // browser & node.js 125 onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) { 126 // Do whatever you want with the Axios progress event 127 }, 128 129 // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js 130 maxContentLength: 2000, 131 132 // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed 133 maxBodyLength: 2000, 134 135 // `validateStatus` defines whether to resolve or reject the promise for a given 136 // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` 137 // or `undefined`), the promise will be resolved; otherwise, the promise will be 138 // rejected. 139 validateStatus: function (status) { 140 return status >= 200 && status < 300; // default 141 }, 142 143 // `maxRedirects` defines the maximum number of redirects to follow in node.js. 144 // If set to 0, no redirects will be followed. 145 maxRedirects: 21, // default 146 147 // `beforeRedirect` defines a function that will be called before redirect. 148 // Use this to adjust the request options upon redirecting, 149 // to inspect the latest response headers, 150 // or to cancel the request by throwing an error 151 // If maxRedirects is set to 0, `beforeRedirect` is not used. 152 beforeRedirect: (options, { headers }) => { 153 if (options.hostname === "example.com") { 154 options.auth = "user:password"; 155 } 156 }, 157 158 // `socketPath` defines a UNIX Socket to be used in node.js. 159 // e.g. '/var/run/docker.sock' to send requests to the docker daemon. 160 // Only either `socketPath` or `proxy` can be specified. 161 // If both are specified, `socketPath` is used. 162 socketPath: null, // default 163 164 // `transport` determines the transport method that will be used to make the request. If defined, it will be used. Otherwise, if `maxRedirects` is 0, the default `http` or `https` library will be used, depending on the protocol specified in `protocol`. Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol, which can handle redirects. 165 transport: undefined, // default 166 167 // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http 168 // and https requests, respectively, in node.js. This allows options to be added like 169 // `keepAlive` that are not enabled by default. 170 httpAgent: new http.Agent({ keepAlive: true }), 171 httpsAgent: new https.Agent({ keepAlive: true }), 172 173 // `proxy` defines the hostname, port, and protocol of the proxy server. 174 // You can also define your proxy using the conventional `http_proxy` and 175 // `https_proxy` environment variables. If you are using environment variables 176 // for your proxy configuration, you can also define a `no_proxy` environment 177 // variable as a comma-separated list of domains that should not be proxied. 178 // Use `false` to disable proxies, ignoring environment variables. 179 // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and 180 // supplies credentials. 181 // This will set an `Proxy-Authorization` header, overwriting any existing 182 // `Proxy-Authorization` custom headers you have set using `headers`. 183 // If the proxy server uses HTTPS, then you must set the protocol to `https`. 184 proxy: { 185 protocol: 'https', 186 host: '127.0.0.1', 187 // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined 188 port: 9000, 189 auth: { 190 username: 'mikeymike', 191 password: 'rapunz3l' 192 } 193 }, 194 195 // `cancelToken` specifies a cancel token that can be used to cancel the request 196 // (see Cancellation section below for details) 197 cancelToken: new CancelToken(function (cancel) { 198 }), 199 200 // an alternative way to cancel Axios requests using AbortController 201 signal: new AbortController().signal, 202 203 // `decompress` indicates whether or not the response body should be decompressed 204 // automatically. If set to `true` will also remove the 'content-encoding' header 205 // from the responses objects of all decompressed responses 206 // - Node only (XHR cannot turn off decompression) 207 decompress: true, // default 208 209 // `insecureHTTPParser` boolean. 210 // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers. 211 // This may allow interoperability with non-conformant HTTP implementations. 212 // Using the insecure parser should be avoided. 213 // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback 214 // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none 215 insecureHTTPParser: undefined, // default 216 217 // transitional options for backward compatibility that may be removed in the newer versions 218 transitional: { 219 // silent JSON parsing mode 220 // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour) 221 // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json') 222 silentJSONParsing: true, // default value for the current Axios version 223 224 // try to parse the response string as JSON even if `responseType` is not 'json' 225 forcedJSONParsing: true, 226 227 // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts 228 clarifyTimeoutError: false, 229 }, 230 231 env: { 232 // The FormData class to be used to automatically serialize the payload into a FormData object 233 FormData: window?.FormData || global?.FormData 234 }, 235 236 formSerializer: { 237 visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values 238 dots: boolean; // use dots instead of brackets format 239 metaTokens: boolean; // keep special endings like {} in parameter key 240 indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes 241 }, 242 243 // http adapter only (node.js) 244 maxRate: [ 245 100 * 1024, // 100KB/s upload limit, 246 100 * 1024 // 100KB/s download limit 247 ] 248}
The response for a request contains the following information.
1{ 2 // `data` is the response that was provided by the server 3 data: {}, 4 5 // `status` is the HTTP status code from the server response 6 status: 200, 7 8 // `statusText` is the HTTP status message from the server response 9 statusText: 'OK', 10 11 // `headers` the HTTP headers that the server responded with 12 // All header names are lowercase and can be accessed using the bracket notation. 13 // Example: `response.headers['content-type']` 14 headers: {}, 15 16 // `config` is the config that was provided to `axios` for the request 17 config: {}, 18 19 // `request` is the request that generated this response 20 // It is the last ClientRequest instance in node.js (in redirects) 21 // and an XMLHttpRequest instance in the browser 22 request: {} 23}
When using then
, you will receive the response as follows:
1axios.get('/user/12345') 2 .then(function (response) { 3 console.log(response.data); 4 console.log(response.status); 5 console.log(response.statusText); 6 console.log(response.headers); 7 console.log(response.config); 8 });
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.
You can specify config defaults that will be applied to every request.
1axios.defaults.baseURL = 'https://api.example.com'; 2 3// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them. 4// See below for an example using Custom instance defaults instead. 5axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 6 7axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
1// Set config defaults when creating the instance 2const instance = axios.create({ 3 baseURL: 'https://api.example.com' 4}); 5 6// Alter defaults after instance has been created 7instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
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.
1// Create an instance using the config defaults provided by the library 2// At this point the timeout config value is `0` as is the default for the library 3const instance = axios.create(); 4 5// Override timeout default for the library 6// Now all requests using this instance will wait 2.5 seconds before timing out 7instance.defaults.timeout = 2500; 8 9// Override timeout for this request as it's known to take a long time 10instance.get('/longRequest', { 11 timeout: 5000 12});
You can intercept requests or responses before they are handled by then
or catch
.
1// Add a request interceptor 2axios.interceptors.request.use(function (config) { 3 // Do something before request is sent 4 return config; 5 }, function (error) { 6 // Do something with request error 7 return Promise.reject(error); 8 }); 9 10// Add a response interceptor 11axios.interceptors.response.use(function (response) { 12 // Any status code that lie within the range of 2xx cause this function to trigger 13 // Do something with response data 14 return response; 15 }, function (error) { 16 // Any status codes that falls outside the range of 2xx cause this function to trigger 17 // Do something with response error 18 return Promise.reject(error); 19 });
If you need to remove an interceptor later you can.
1const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 2axios.interceptors.request.eject(myInterceptor);
You can also clear all interceptors for requests or responses.
1const instance = axios.create(); 2instance.interceptors.request.use(function () {/*...*/}); 3instance.interceptors.request.clear(); // Removes interceptors from requests 4instance.interceptors.response.use(function () {/*...*/}); 5instance.interceptors.response.clear(); // Removes interceptors from responses
You can add interceptors to a custom instance of axios.
1const instance = axios.create(); 2instance.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.
1axios.interceptors.request.use(function (config) { 2 config.headers.test = 'I am only a header!'; 3 return config; 4}, 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 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.
1function onGetCall(config) { 2 return config.method === 'get'; 3} 4axios.interceptors.request.use(function (config) { 5 config.headers.test = 'special get headers'; 6 return config; 7}, null, { runWhen: onGetCall });
Note: options parameter(having
synchronous
andrunWhen
properties) is only supported for request interceptors at the moment.
Given you add multiple response interceptors and when the response was fulfilled
Read the interceptor tests for seeing all this in code.
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 or unsupported value provided in axios configuration. |
ERR_BAD_OPTION | Invalid option provided in axios configuration. |
ECONNABORTED | Request timed out due to exceeding timeout specified in axios configuration. |
ETIMEDOUT | Request timed out due to exceeding default axios timelimit. |
ERR_NETWORK | Network-related issue. |
ERR_FR_TOO_MANY_REDIRECTS | Request is redirected too many times; exceeds max redirects specified in axios configuration. |
ERR_DEPRECATED | Deprecated feature or method used in axios. |
ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. |
ERR_BAD_REQUEST | Requested has unexpected format or missing required parameters. |
ERR_CANCELED | Feature or method is canceled explicitly by the user. |
ERR_NOT_SUPPORT | Feature or method not supported in the current axios environment. |
ERR_INVALID_URL | Invalid URL provided for axios request. |
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.
1axios.get('/user/12345') 2 .catch(function (error) { 3 if (error.response) { 4 // The request was made and the server responded with a status code 5 // that falls out of the range of 2xx 6 console.log(error.response.data); 7 console.log(error.response.status); 8 console.log(error.response.headers); 9 } else if (error.request) { 10 // The request was made but no response was received 11 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of 12 // http.ClientRequest in node.js 13 console.log(error.request); 14 } else { 15 // Something happened in setting up the request that triggered an Error 16 console.log('Error', error.message); 17 } 18 console.log(error.config); 19 });
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.
1axios.get('/user/12345', { 2 validateStatus: function (status) { 3 return status < 500; // Resolve only if the status code is less than 500 4 } 5})
Using toJSON
you get an object with more information about the HTTP error.
1axios.get('/user/12345') 2 .catch(function (error) { 3 console.log(error.toJSON()); 4 });
Starting from v0.22.0
Axios supports AbortController to cancel requests in fetch API way:
1const controller = new AbortController(); 2 3axios.get('/foo/bar', { 4 signal: controller.signal 5}).then(function(response) { 6 //... 7}); 8// cancel the request 9controller.abort()
👎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:
1const CancelToken = axios.CancelToken; 2const source = CancelToken.source(); 3 4axios.get('/user/12345', { 5 cancelToken: source.token 6}).catch(function (thrown) { 7 if (axios.isCancel(thrown)) { 8 console.log('Request canceled', thrown.message); 9 } else { 10 // handle error 11 } 12}); 13 14axios.post('/user/12345', { 15 name: 'new name' 16}, { 17 cancelToken: source.token 18}) 19 20// cancel the request (the message parameter is optional) 21source.cancel('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the CancelToken
constructor:
1const CancelToken = axios.CancelToken; 2let cancel; 3 4axios.get('/user/12345', { 5 cancelToken: new CancelToken(function executor(c) { 6 // An executor function receives a cancel function as a parameter 7 cancel = c; 8 }) 9}); 10 11// cancel the request 12cancel();
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:
application/x-www-form-urlencoded
formatBy 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).
1const params = new URLSearchParams({ foo: 'bar' }); 2params.append('extraparam', 'value'); 3axios.post('/foo', params);
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:
1const qs = require('qs'); 2axios.post('/foo', qs.stringify({ 'bar': 123 }));
Or in another way (ES6),
1import qs from 'qs'; 2const data = { 'bar': 123 }; 3const options = { 4 method: 'POST', 5 headers: { 'content-type': 'application/x-www-form-urlencoded' }, 6 data: qs.stringify(data), 7 url, 8}; 9axios(options);
For older Node.js engines, you can use the querystring
module as follows:
1const querystring = require('querystring'); 2axios.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 thequerystring
method has known issues with that use case.
Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".
1const data = { 2 x: 1, 3 arr: [1, 2, 3], 4 arr2: [1, [2], 3], 5 users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], 6}; 7 8await axios.postForm('https://postman-echo.com/post', data, 9 {headers: {'content-type': 'application/x-www-form-urlencoded'}} 10);
The server will handle it as:
1 { 2 x: '1', 3 'arr[]': [ '1', '2', '3' ], 4 'arr2[0]': '1', 5 'arr2[1][0]': '2', 6 'arr2[2]': '3', 7 'arr3[]': [ '1', '2', '3' ], 8 'users[0][name]': 'Peter', 9 'users[0][surname]': 'griffin', 10 'users[1][name]': 'Thomas', 11 'users[1][surname]': 'Anderson' 12 }
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
1 var app = express(); 2 3 app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies 4 5 app.post('/', function (req, res, next) { 6 // echo body as JSON 7 res.send(JSON.stringify(req.body)); 8 }); 9 10 server = app.listen(3000);
multipart/form-data
formatTo 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.
1const formData = new FormData(); 2formData.append('foo', 'bar'); 3 4axios.post('https://httpbin.org/post', formData);
In node.js, you can use the form-data
library as follows:
1const FormData = require('form-data'); 2 3const form = new FormData(); 4form.append('my_field', 'my value'); 5form.append('my_buffer', new Buffer(10)); 6form.append('my_file', fs.createReadStream('/foo/bar.jpg')); 7 8axios.post('https://example.com', form)
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):
1import axios from 'axios'; 2 3axios.post('https://httpbin.org/post', {x: 1}, { 4 headers: { 5 'Content-Type': 'multipart/form-data' 6 } 7}).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:
1const axios = require('axios'); 2var FormData = require('form-data'); 3 4axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, { 5 headers: { 6 'Content-Type': 'multipart/form-data' 7 } 8}).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 keyNote: 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:
1const obj = { 2 x: 1, 3 arr: [1, 2, 3], 4 arr2: [1, [2], 3], 5 users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], 6 'obj2{}': [{x:1}] 7};
The following steps will be executed by the Axios serializer internally:
1const formData = new FormData(); 2formData.append('x', '1'); 3formData.append('arr[]', '1'); 4formData.append('arr[]', '2'); 5formData.append('arr[]', '3'); 6formData.append('arr2[0]', '1'); 7formData.append('arr2[1][0]', '2'); 8formData.append('arr2[2]', '3'); 9formData.append('users[0][name]', 'Peter'); 10formData.append('users[0][surname]', 'Griffin'); 11formData.append('users[1][name]', 'Thomas'); 12formData.append('users[1][surname]', 'Anderson'); 13formData.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
.
You can easily submit a single file:
1await axios.postForm('https://httpbin.org/post', { 2 'myVar' : 'foo', 3 'file': document.querySelector('#fileInput').files[0] 4});
or multiple files as multipart/form-data
:
1await axios.postForm('https://httpbin.org/post', { 2 'files[]': document.querySelector('#fileInput').files 3});
FileList
object can be passed directly:
1await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
All files will be sent with the same field names: files[]
.
Pass HTML Form element as a payload to submit it as multipart/form-data
content.
1await 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
:
1await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), { 2 headers: { 3 'Content-Type': 'application/json' 4 } 5})
For example, the Form
1<form id="form"> 2 <input type="text" name="foo" value="1"> 3 <input type="text" name="deep.prop" value="2"> 4 <input type="text" name="deep prop spaced" value="3"> 5 <input type="text" name="baz" value="4"> 6 <input type="text" name="baz" value="5"> 7 8 <select name="user.age"> 9 <option value="value1">Value 1</option> 10 <option value="value2" selected>Value 2</option> 11 <option value="value3">Value 3</option> 12 </select> 13 14 <input type="submit" value="Save"> 15</form>
will be submitted as the following JSON object:
1{ 2 "foo": "1", 3 "deep": { 4 "prop": { 5 "spaced": "3" 6 } 7 }, 8 "baz": [ 9 "4", 10 "5" 11 ], 12 "user": { 13 "age": "value2" 14 } 15}
Sending Blobs
/Files
as JSON (base64
) is not currently supported.
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.
1await axios.post(url, data, { 2 onUploadProgress: function (axiosProgressEvent) { 3 /*{ 4 loaded: number; 5 total?: number; 6 progress?: number; // in range [0..1] 7 bytes: number; // how many bytes have been transferred since the last trigger (delta) 8 estimated?: number; // estimated time in seconds 9 rate?: number; // upload speed in bytes 10 upload: true; // upload sign 11 }*/ 12 }, 13 14 onDownloadProgress: function (axiosProgressEvent) { 15 /*{ 16 loaded: number; 17 total?: number; 18 progress?: number; 19 bytes: number; 20 estimated?: number; 21 rate?: number; // download speed in bytes 22 download: true; // download sign 23 }*/ 24 } 25});
You can also track stream upload/download progress in node.js:
1const {data} = await axios.post(SERVER_URL, readableStream, { 2 onUploadProgress: ({progress}) => { 3 console.log((progress * 100).toFixed(2)); 4 }, 5 6 headers: { 7 'Content-Length': contentLength 8 }, 9 10 maxRedirects: 0 // avoid buffering the entire stream 11});
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.
Download and upload rate limits can only be set for the http adapter (node.js):
1const {data} = await axios.post(LOCAL_SERVER_URL, myBuffer, { 2 onUploadProgress: ({progress, rate}) => { 3 console.log(`Upload [${(progress*100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`) 4 }, 5 6 maxRate: [100 * 1024], // 100KB/s limit 7});
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.
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 servernull
- skip header when rendering to JSONfalse
- 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 setNote: 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) => { 2 request.headers.set('My-header', 'value'); 3 4 request.headers.set({ 5 "My-set-header1": "my-set-value1", 6 "My-set-header2": "my-set-value2" 7 }); 8 9 request.headers.set('User-Agent', false); // disable subsequent setting the header by Axios 10 11 request.headers.setContentType('text/plain'); 12 13 request.headers['My-set-header2'] = 'newValue' // direct access is deprecated 14 15 return request; 16 } 17 );
You can iterate over an AxiosHeaders
instance using a for...of
statement:
1const headers = new AxiosHeaders({ 2 foo: '1', 3 bar: '2', 4 baz: '3' 5}); 6 7for(const [header, value] of headers) { 8 console.log(header, value); 9} 10 11// foo 1 12// bar 2 13// baz 3
Constructs a new AxiosHeaders
instance.
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
If the headers object is a string, it will be parsed as RAW HTTP headers.
1const headers = new AxiosHeaders(` 2Host: www.bing.com 3User-Agent: curl/7.54.0 4Accept: */*`); 5 6console.log(headers); 7 8// Object [AxiosHeaders] { 9// host: 'www.bing.com', 10// 'user-agent': 'curl/7.54.0', 11// accept: '*/*' 12// }
1set(headerName, value: Axios, rewrite?: boolean); 2set(headerName, value, rewrite?: (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean); 3set(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 anywayThe option can also accept a user-defined function that determines whether the value should be overwritten or not.
Returns this
.
get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue;
get(headerName: string, parser: RegExp): RegExpExecArray | null;
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.
1const headers = new AxiosHeaders({ 2 'Content-Type': 'multipart/form-data; boundary=Asrf456BGe4h' 3}); 4 5console.log(headers.get('Content-Type')); 6// multipart/form-data; boundary=Asrf456BGe4h 7 8console.log(headers.get('Content-Type', true)); // parse key-value pairs from a string separated with \s,;= delimiters: 9// [Object: null prototype] { 10// 'multipart/form-data': undefined, 11// boundary: 'Asrf456BGe4h' 12// } 13 14 15console.log(headers.get('Content-Type', (value, name, headers) => { 16 return String(value).replace(/a/g, 'ZZZ'); 17})); 18// multipZZZrt/form-dZZZtZZZ; boundZZZry=Asrf456BGe4h 19 20console.log(headers.get('Content-Type', /boundary=(\w+)/)?.[0]); 21// boundary=Asrf456BGe4h 22
Returns the value of the header.
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
Returns true
if the header is set (has no undefined
value).
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
Returns true
if at least one header has been removed.
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.
1const headers = new AxiosHeaders({ 2 'foo': '1', 3 'x-foo': '2', 4 'x-bar': '3', 5}); 6 7console.log(headers.clear(/^x-/)); // true 8 9console.log(headers.toJSON()); // [Object: null prototype] { foo: '1' }
Returns true
if at least one header has been cleared.
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
)
1const headers = new AxiosHeaders({ 2 'foo': '1', 3}); 4 5headers.Foo = '2'; 6headers.FOO = '3'; 7 8console.log(headers.toJSON()); // [Object: null prototype] { foo: '1', Foo: '2', FOO: '3' } 9console.log(headers.normalize().toJSON()); // [Object: null prototype] { foo: '3' } 10console.log(headers.normalize(true).toJSON()); // [Object: null prototype] { Foo: '3' }
Returns this
.
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.
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.
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.
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
Returns a new AxiosHeaders
instance created by merging the target objects.
The following shortcuts are available:
setContentType
, getContentType
, hasContentType
setContentLength
, getContentLength
, hasContentLength
setAccept
, getAccept
, hasAccept
setUserAgent
, getUserAgent
, hasUserAgent
setContentEncoding
, getContentEncoding
, hasContentEncoding
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:
1const {data} = axios.get(url, { 2 adapter: 'fetch' // by default ['xhr', 'http', 'fetch'] 3})
You can create a separate instance for this:
1const fetchAxios = axios.create({ 2 adapter: 'fetch' 3}); 4 5const {data} = fetchAxios.get(url);
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).
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 TypeScript definitions and a type guard for axios errors.
1let user: User = null; 2try { 3 const { data } = await axios.get('/user?ID=12345'); 4 user = data.userDetails; 5} catch (error) { 6 if (axios.isAxiosError(error)) { 7 handleAxiosError(error); 8 } else { 9 handleUnexpectedError(error); 10 } 11}
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"
.
You can use Gitpod, an online IDE(which is free for Open Source) for contributing or running the examples online.
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.
Stable Version
3
0/10
Summary
Server-Side Request Forgery in axios
Affected Versions
>= 1.3.2, <= 1.7.3
Patched Versions
1.7.4
7.5/10
Summary
axios Inefficient Regular Expression Complexity vulnerability
Affected Versions
< 0.21.2
Patched Versions
0.21.2
7.5/10
Summary
Denial of Service in axios
Affected Versions
<= 0.18.0
Patched Versions
0.18.1
3
6.5/10
Summary
Axios Cross-Site Request Forgery Vulnerability
Affected Versions
>= 0.8.1, < 0.28.0
Patched Versions
0.28.0
6.5/10
Summary
Axios Cross-Site Request Forgery Vulnerability
Affected Versions
>= 1.0.0, < 1.6.0
Patched Versions
1.6.0
5.9/10
Summary
Axios vulnerable to Server-Side Request Forgery
Affected Versions
< 0.21.1
Patched Versions
0.21.1
Reason
no dangerous workflow patterns detected
Reason
30 commit(s) and 7 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
security policy file detected
Details
Reason
license file detected
Details
Reason
SAST tool detected but not run on all commits
Details
Reason
Found 12/19 approved changesets -- score normalized to 6
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details