For some bundlers and some ES6 linter's you may need to do the following:
1import { defaultas 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:
Note: CommonJS usage
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with require(), use the following approach:
1import axios from 'axios';
2//const axios = require('axios'); // legacy way34// Make a request for a user with a given ID5axios.get('/user?ID=12345')
6 .then(function(response) {7// handle success8 console.log(response);
9 })
10 .catch(function(error) {11// handle error12 console.log(error);
13 })
14 .finally(function() {15// always executed16 });
1718// Optionally the request above could also be done as19axios.get('/user', {
20 params: {
21 ID: 1234522 }
23 })
24 .then(function(response) {25 console.log(response);
26 })
27 .catch(function(error) {28 console.log(error);
29 })
30 .finally(function() {31// always executed32 });
3334// Want to use async/await? Add the `async` keyword to your outer function/method.35async functiongetUser() {36try {
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.
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{
2 // `url` is the server URL that will be used for the request
3 url: '/user',
45 // `method` is the request method to be used when making the request
6 method: 'get', // default
78 // `baseURL` will be prepended to `url` unless `url` is absolute.
9 // It can be convenient to set`baseURL`for an instanceof axios to pass relative URLs
10 // to methods of that instance.
11 baseURL: 'https://some-domain.com/api/',
1213 // `transformRequest` allows changes to the request databefore it is sent to the server14 // This isonly applicable for request methods 'PUT', 'POST', 'PATCH'and'DELETE'15 // The lastfunctionin the array must return a stringor an instanceof 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 data2021returndata;
22 }],
2324 // `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 data2829returndata;
30 }],
3132 // `headers` are custom headers to be sent
33 headers: {'X-Requested-With': 'XMLHttpRequest'},
3435 // `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 },
4041 // `paramsSerializer` is an optional config that allows you to customize serializing `params`.
42 paramsSerializer: {
4344 //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 */ },
4647 // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.
48 serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),
4950 //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 },
5354 // `data` is the data to be sent as the request body
55 // Only applicable for request methods 'PUT', 'POST', 'DELETE , and'PATCH'56 // Whenno`transformRequest`isset, must be of one of the following types:
57 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
58 // - Browser only: FormData, File, Blob59 // - Node only: Stream, Buffer, FormData (form-datapackage)
60data: {
61 firstName: 'Fred'62 },
6364 // syntax alternative to send datainto the body65 // method post
66 // only the valueis sent, not the key67data: 'Country=Brasil&City=Belo Horizonte',
6869 // `timeout` specifies the numberof milliseconds before the request times out.
70 // If the request takes longer than`timeout`, the request will be aborted.
71timeout: 1000, // defaultis`0` (notimeout)
7273 // `withCredentials` indicates whether ornotcross-site Access-Control requests
74 // should be made using credentials
75 withCredentials: false, // default7677 // `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 nameof the built-in adapter, or provide an arraywith their names83 // tochoose the first available in the environment
84 adapter: 'xhr' // 'fetch' | 'http' | ['xhr', 'http', 'fetch']
8586 // `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 setusing`headers`.
89 // Please note that onlyHTTP Basic auth is configurable through this parameter.
90 // For Bearer tokens and such, use`Authorization` custom headers instead.
91 auth: {
92 username: 'janedoe',
93password: 's00pers3cret'94 },
9596 // `responseType` indicates the typeofdata that the server will respond with97 // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'98 // browser only: 'blob'99 responseType: 'json', // default100101 // `responseEncoding` indicates encodingtousefor decoding responses (Node.js only)
102 // Note: Ignored for`responseType`of'stream'orclient-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', // default107108 // `xsrfCookieName`is the nameof the cookie touseas a valuefor xsrf token
109 xsrfCookieName: 'XSRF-TOKEN', // default110111 // `xsrfHeaderName`is the nameof the http header that carries the xsrf token value112 xsrfHeaderName: 'X-XSRF-TOKEN', // default113114 // `undefined` (default) - set XSRF header onlyfor the same origin requests
115 withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),
116117 // `onUploadProgress` allows handling of progress eventsfor 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 event121 },
122123 // `onDownloadProgress` allows handling of progress eventsfor 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 event127 },
128129 // `maxContentLength` defines the maxsizeof the http response contentinbytes allowed in node.js
130 maxContentLength: 2000,
131132 // `maxBodyLength` (Node onlyoption) defines the maxsizeof the http request contentinbytes allowed
133 maxBodyLength: 2000,
134135 // `validateStatus` defines whether to resolve orreject the promise for a given
136 // HTTP response status code. If`validateStatus`returns`true` (orissetto`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 },
142143 // `maxRedirects` defines the maximum number of redirects to follow in node.js.
144 // If setto0, no redirects will be followed.
145 maxRedirects: 21, // default146147 // `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 // ortocancel the request by throwing an error151 // If maxRedirects issetto0, `beforeRedirect`isnot used.
152 beforeRedirect: (options, { headers }) => {
153if (options.hostname === "example.com") {
154 options.auth = "user:password";
155 }
156 },
157158 // `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
163164 // `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
166167 // `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 }),
172173 // `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`todisable proxies, ignoring environment variables.
179 // `auth` indicates that HTTP Basic auth should be used toconnectto the proxy, and180 // supplies credentials.
181 // This will set an `Proxy-Authorization` header, overwriting any existing
182 // `Proxy-Authorization` custom headers you have setusing`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'ifbothare defined
188 port: 9000,
189 auth: {
190 username: 'mikeymike',
191password: 'rapunz3l'192 }
193 },
194195 // `cancelToken` specifies a cancel token that can be used tocancel the request
196 // (see Cancellation section below for details)
197 cancelToken: new CancelToken(function (cancel) {
198 }),
199200 // an alternative way tocancel Axios requests using AbortController
201 signal: new AbortController().signal,
202203 // `decompress` indicates whether ornot the response body should be decompressed
204 // automatically. Ifsetto`true` will also remove the 'content-encoding' header
205 // from the responses objects ofall decompressed responses
206 // - Node only (XHR cannot turn off decompression)
207 decompress: true, // default208209 // `insecureHTTPParser` boolean.
210 // Indicates wheretouse 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_callback214 // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none215 insecureHTTPParser: undefined, // default216217 // transitional options for backward compatibility that may be removed in the newer versions218 transitional: {
219 // silent JSON parsing mode220 // `true` - ignoreJSON parsing errorsandset response.data tonullif parsing failed (old behaviour)
221 // `false` - throw SyntaxError ifJSON parsing failed (Note: responseType must be setto'json')
222 silentJSONParsing: true, // defaultvaluefor the current Axios version223224 // try toparse the response stringasJSON even if`responseType`isnot'json'225 forcedJSONParsing: true,
226227 // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
228 clarifyTimeoutError: false,
229 },
230231 env: {
232 // The FormData classto be used to automatically serialize the payload into a FormData object233 FormData: window?.FormData || global?.FormData
234 },
235236 formSerializer: {
237 visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values238 dots: boolean; // use dots instead of brackets format239 metaTokens: boolean; // keep special endings like {} in parameter key
240 indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets withindexes241 },
242243 // http adapter only (node.js)
244 maxRate: [
245100 * 1024, // 100KB/s upload limit,
246100 * 1024 // 100KB/s download limit247 ]
248}
Response Schema
The response for a request contains the following information.
1{
2// `data` is the response that was provided by the server3 data: {},
45// `status` is the HTTP status code from the server response6 status: 200,
78// `statusText` is the HTTP status message from the server response9 statusText: 'OK',
1011// `headers` the HTTP headers that the server responded with12// All header names are lowercase and can be accessed using the bracket notation.13// Example: `response.headers['content-type']`14 headers: {},
1516// `config` is the config that was provided to `axios` for the request17 config: {},
1819// `request` is the request that generated this response20// It is the last ClientRequest instance in node.js (in redirects)21// and an XMLHttpRequest instance in the browser22 request: {}
23}
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
1axios.defaults.baseURL = 'https://api.example.com';
23// 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;
67axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Custom instance defaults
1// Set config defaults when creating the instance
2const instance = axios.create({
3 baseURL: 'https://api.example.com'
4});
56// Alter defaults after instance has been created
7instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Config order of precedence
Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here's an example.
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 library3const instance = axios.create();
45// 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;
89// Override timeout for this request as it's known to take a long time
10instance.get('/longRequest', {
11 timeout: 5000
12});
Interceptors
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 requestis sent
4 return config;
5 }, function (error) {
6 // Do something withrequesterror7 return Promise.reject(error);
8 });
910// Add a response interceptor
11axios.interceptors.response.use(function (response) {
12 // Any status code that lie within the range of 2xx cause this functionto trigger
13 // Do something withresponse data
14 return response;
15 }, function (error) {
16 // Any status codes that falls outside the range of 2xx cause this functionto trigger
17 // Do something withresponseerror18 return Promise.reject(error);
19 });
If you need to remove an interceptor later you can.
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!';
3returnconfig;
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.
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.
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.
1axios.get('/user/12345')
2 .catch(function (error) {
3if (error.response) {
4// The request was made and the server responded with a status code5// that falls out of the range of 2xx6 console.log(error.response.data);
7 console.log(error.response.status);
8 console.log(error.response.headers);
9 } elseif (error.request) {
10// The request was made but no response was received11// `error.request` is an instance of XMLHttpRequest in the browser and an instance of12// http.ClientRequest in node.js13 console.log(error.request);
14 } else {
15// Something happened in setting up the request that triggered an Error16 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) {3return status < 500; // Resolve onlyif the status code is less than 5004 }
5})
Using toJSON you get an object with more information about the HTTP error.
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();34axios.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});1314axios.post('/user/12345', {
15 name: 'new name'
16}, {
17 cancelToken: source.token
18})
1920// 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;
34axios.get('/user/12345', {
5 cancelToken: new CancelToken(functionexecutor(c) {6 // An executor function receives a cancel function as a parameter7cancel = c;
8 })
9});
1011// cancel the request12cancel();
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:
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();23 app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies45 app.post('/', function (req, res, next) {
6 // echo body as JSON
7 res.send(JSON.stringify(req.body));8 });910 server = app.listen(3000);
Using multipart/form-data format
FormData
To send the data as a multipart/formdata you need to pass a formData instance as a payload.
Setting the Content-Type header is not required as Axios guesses it based on the payload type.
1const formData = new FormData();2formData.append('foo', 'bar');34axios.post('https://httpbin.org/post', formData);
In node.js, you can use the form-data library as follows:
1const FormData = require('form-data');23const 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'));78axios.post('https://example.com', form)
🆕 Automatic serialization to FormData
Starting from v0.27.0, Axios supports automatic object serialization to a FormData object if the request Content-Type
header is set to multipart/form-data.
The following request will submit the data in a FormData format (Browser & Node.js):
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
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.
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.
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 sign11 }*/
12 },
1314 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 sign23 }*/
24 }
25});
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):
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:
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 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)
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?)
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.
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.
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:
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).
Semver
Until axios reaches a 1.0 release, breaking changes will be released with a new minor version. For example 0.5.1, and 0.5.4 will have the same API, but 0.6.0 will have breaking changes.
Promises
axios depends on a native ES6 Promise implementation to be supported.
If your environment doesn't support ES6 Promises, you can polyfill.
TypeScript
axios includes TypeScript definitions and a type guard for axios errors.
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.
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.
Info: Found disclosure, vulnerability, and/or timelines in security policy: SECURITY.md:1
Info: Found text in security policy: SECURITY.md:1
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Info: project has a license file: LICENSE:0
Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
SAST tool detected but not run on all commits
Details
Info: SAST configuration detected: CodeQL
Warn: 25 commits out of 28 are checked with a SAST tool
Reason
Found 9/14 approved changesets -- score normalized to 6
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:30: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/ci.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:35: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/ci.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:43: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/ci.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:53: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/ci.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:35: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/codeql-analysis.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/codeql-analysis.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:47: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/codeql-analysis.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/depsreview.yaml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/depsreview.yaml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/depsreview.yaml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/depsreview.yaml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/notify.yml:35: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/notify.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/notify.yml:43: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/notify.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-tag.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/npm-tag.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-tag.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/npm-tag.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/pr.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/pr.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/pr.yml:30: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/pr.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/pr.yml:50: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/pr.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/pr.yml:53: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/pr.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/pr.yml:56: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/pr.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/pr.yml:60: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/pr.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/publish.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/publish.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/publish.yml:33: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/publish.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/publish.yml:36: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/publish.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/publish.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/publish.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/publish.yml:51: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/publish.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:67: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/publish.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:75: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/publish.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/sponsors.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/sponsors.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/sponsors.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/sponsors.yml/v1.x?enable=pin
Warn: third-party GitHubAction not pinned by hash: .github/workflows/sponsors.yml:47: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/sponsors.yml/v1.x?enable=pin
Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/stale.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/axios/axios/stale.yml/v1.x?enable=pin
Info: 0 out of 20 GitHub-owned GitHubAction dependencies pinned
Info: 0 out of 11 third-party GitHubAction dependencies pinned
Info: 6 out of 6 npmCommand dependencies pinned
Reason
detected GitHub workflow tokens with excessive permissions
Details
Info: jobLevel 'contents' permission set to 'read': .github/workflows/codeql-analysis.yml:25
Info: jobLevel 'actions' permission set to 'read': .github/workflows/codeql-analysis.yml:24
Warn: jobLevel 'contents' permission set to 'write': .github/workflows/npm-tag.yml:14
Warn: jobLevel 'contents' permission set to 'write': .github/workflows/publish.yml:15
Info: topLevel 'contents' permission set to 'read': .github/workflows/ci.yml:18
Warn: no topLevel permission defined: .github/workflows/codeql-analysis.yml:1
Info: topLevel 'contents' permission set to 'read': .github/workflows/depsreview.yaml:5
Warn: no topLevel permission defined: .github/workflows/notify.yml:1
Warn: no topLevel permission defined: .github/workflows/npm-tag.yml:1
Warn: no topLevel permission defined: .github/workflows/pr.yml:1
Warn: no topLevel permission defined: .github/workflows/publish.yml:1
Warn: no topLevel permission defined: .github/workflows/sponsors.yml:1
Warn: no topLevel permission defined: .github/workflows/stale.yml:1
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Warn: no fuzzer integrations found
Reason
26 existing vulnerabilities detected
Details
Warn: Project is vulnerable to: GHSA-v88g-cgmw-v5xw
Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
Warn: Project is vulnerable to: GHSA-x9w5-v3q2-3rhw
Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
Warn: Project is vulnerable to: GHSA-wm7h-9275-46v2
Warn: Project is vulnerable to: GHSA-4gmj-3p3h-gm8h
Warn: Project is vulnerable to: GHSA-pfrx-2q88-qq97
Warn: Project is vulnerable to: GHSA-rc47-6667-2j5j
Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
Warn: Project is vulnerable to: GHSA-rhx6-c78j-4q9w
Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
Warn: Project is vulnerable to: GHSA-44c6-4v22-4mhx
Warn: Project is vulnerable to: GHSA-4x5v-gmq8-25ch
Warn: Project is vulnerable to: GHSA-3jfq-g458-7qm9
Warn: Project is vulnerable to: GHSA-5955-9wpr-37jh
Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
Warn: Project is vulnerable to: GHSA-cchq-frgv-rjh5
Warn: Project is vulnerable to: GHSA-g644-9gfx-q4q4
Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Score
5.9
/10
Last Scanned on 2025-01-13
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.