Axios

Promise based HTTP client for the browser and node.js

README

axios

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

Promise based HTTP client for the browser and node.js

New axios docs website: click here


Table of Contents


  - Features
  - Example
  - Axios API
    - AbortController
    - URLSearchParams
    - Query string
    - FormData
  - Semver
  - Promises
  - Resources
  - Credits
  - License

Features


- Make XMLHttpRequests from the browser
- Make http requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Automatic transforms for JSON data
- 🆕 Automatic data object serialization to multipart/form-data and x-www-form-urlencoded body encodings
- Client side support for protecting against XSRF

Browser Support


Chrome | Firefox | Safari | Opera | Edge | IE |
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
Browser Matrix

Installing


Using npm:

  1. ``` sh
  2. $ npm install axios
  3. ```

Using bower:

  1. ``` sh
  2. $ bower install axios
  3. ```

Using yarn:

  1. ``` sh
  2. $ yarn add axios
  3. ```

Using pnpm:

  1. ``` sh
  2. $ pnpm add axios
  3. ```

Using jsDelivr CDN:

  1. ``` html
  2. <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  3. ```

Using unpkg CDN:

  1. ``` html
  2. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  3. ```

Example


note: CommonJS usage

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

  1. ``` js
  2. const axios = require('axios').default;

  3. // axios. will now provide autocomplete and parameter typings
  4. ```

Performing a GET request

  1. ``` js
  2. const axios = require('axios').default;

  3. // Make a request for a user with a given ID
  4. axios.get('/user?ID=12345')
  5.   .then(function (response) {
  6.     // handle success
  7.     console.log(response);
  8.   })
  9.   .catch(function (error) {
  10.     // handle error
  11.     console.log(error);
  12.   })
  13.   .then(function () {
  14.     // always executed
  15.   });

  16. // Optionally the request above could also be done as
  17. axios.get('/user', {
  18.     params: {
  19.       ID: 12345
  20.     }
  21.   })
  22.   .then(function (response) {
  23.     console.log(response);
  24.   })
  25.   .catch(function (error) {
  26.     console.log(error);
  27.   })
  28.   .then(function () {
  29.     // always executed
  30.   });  

  31. // Want to use async/await? Add the `async` keyword to your outer function/method.
  32. async function getUser() {
  33.   try {
  34.     const response = await axios.get('/user?ID=12345');
  35.     console.log(response);
  36.   } catch (error) {
  37.     console.error(error);
  38.   }
  39. }
  40. ```

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

  1. ``` js
  2. axios.post('/user', {
  3.     firstName: 'Fred',
  4.     lastName: 'Flintstone'
  5.   })
  6.   .then(function (response) {
  7.     console.log(response);
  8.   })
  9.   .catch(function (error) {
  10.     console.log(error);
  11.   });
  12. ```

Performing multiple concurrent requests

  1. ``` js
  2. function getUserAccount() {
  3.   return axios.get('/user/12345');
  4. }

  5. function getUserPermissions() {
  6.   return axios.get('/user/12345/permissions');
  7. }

  8. Promise.all([getUserAccount(), getUserPermissions()])
  9.   .then(function (results) {
  10.     const acct = results[0];
  11.     const perm = results[1];
  12.   });
  13. ```

axios API


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

axios(config)

  1. ``` js
  2. // Send a POST request
  3. axios({
  4.   method: 'post',
  5.   url: '/user/12345',
  6.   data: {
  7.     firstName: 'Fred',
  8.     lastName: 'Flintstone'
  9.   }
  10. });
  11. ```

  1. ``` js
  2. // GET request for remote image in node.js
  3. axios({
  4.   method: 'get',
  5.   url: 'https://bit.ly/2mTM3nY',
  6.   responseType: 'stream'
  7. })
  8.   .then(function (response) {
  9.     response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  10.   });
  11. ```

axios(url[, config])

  1. ``` js
  2. // Send a GET request (default method)
  3. axios('/user/12345');
  4. ```

Request method aliases


For convenience, aliases have been provided for all common request methods.

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

NOTE
When using the alias methods url, method, and data properties don't need to be specified in config.

Concurrency (Deprecated)

Please use Promise.all to replace the below functions.

Helper functions for dealing with concurrent requests.

axios.all(iterable)
axios.spread(callback)

Creating an instance


You can create a new instance of axios with a custom config.

axios.create([config])

  1. ``` js
  2. const instance = axios.create({
  3.   baseURL: 'https://some-domain.com/api/',
  4.   timeout: 1000,
  5.   headers: {'X-Custom-Header': 'foobar'}
  6. });
  7. ```

Instance methods


The available instance methods are listed below. The specified config will be merged with the instance config.

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])

Request Config


These are the available config options for making requests. Only the url is required. Requests will default to GET if method is not specified.

  1. ``` js
  2. {
  3.   // `url` is the server URL that will be used for the request
  4.   url: '/user',

  5.   // `method` is the request method to be used when making the request
  6.   method: 'get', // default

  7.   // `baseURL` will be prepended to `url` unless `url` is absolute.
  8.   // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  9.   // to methods of that instance.
  10.   baseURL: 'https://some-domain.com/api/',

  11.   // `transformRequest` allows changes to the request data before it is sent to the server
  12.   // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  13.   // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  14.   // FormData or Stream
  15.   // You may modify the headers object.
  16.   transformRequest: [function (data, headers) {
  17.     // Do whatever you want to transform the data

  18.     return data;
  19.   }],

  20.   // `transformResponse` allows changes to the response data to be made before
  21.   // it is passed to then/catch
  22.   transformResponse: [function (data) {
  23.     // Do whatever you want to transform the data

  24.     return data;
  25.   }],

  26.   // `headers` are custom headers to be sent
  27.   headers: {'X-Requested-With': 'XMLHttpRequest'},

  28.   // `params` are the URL parameters to be sent with the request
  29.   // Must be a plain object or a URLSearchParams object
  30.   params: {
  31.     ID: 12345
  32.   },

  33.   // `paramsSerializer` is an optional config in charge of serializing `params`
  34.   paramsSerializer: {
  35.     indexes: null // array indexes format (null - no brackets, false - empty brackets, true - brackets with indexes)
  36.   },

  37.   // `data` is the data to be sent as the request body
  38.   // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
  39.   // When no `transformRequest` is set, must be of one of the following types:
  40.   // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  41.   // - Browser only: FormData, File, Blob
  42.   // - Node only: Stream, Buffer
  43.   data: {
  44.     firstName: 'Fred'
  45.   },
  46.   
  47.   // syntax alternative to send data into the body
  48.   // method post
  49.   // only the value is sent, not the key
  50.   data: 'Country=Brasil&City=Belo Horizonte',

  51.   // `timeout` specifies the number of milliseconds before the request times out.
  52.   // If the request takes longer than `timeout`, the request will be aborted.
  53.   timeout: 1000, // default is `0` (no timeout)

  54.   // `withCredentials` indicates whether or not cross-site Access-Control requests
  55.   // should be made using credentials
  56.   withCredentials: false, // default

  57.   // `adapter` allows custom handling of requests which makes testing easier.
  58.   // Return a promise and supply a valid response (see lib/adapters/README.md).
  59.   adapter: function (config) {
  60.     /* ... */
  61.   },

  62.   // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  63.   // This will set an `Authorization` header, overwriting any existing
  64.   // `Authorization` custom headers you have set using `headers`.
  65.   // Please note that only HTTP Basic auth is configurable through this parameter.
  66.   // For Bearer tokens and such, use `Authorization` custom headers instead.
  67.   auth: {
  68.     username: 'janedoe',
  69.     password: 's00pers3cret'
  70.   },

  71.   // `responseType` indicates the type of data that the server will respond with
  72.   // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  73.   //   browser only: 'blob'
  74.   responseType: 'json', // default

  75.   // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
  76.   // Note: Ignored for `responseType` of 'stream' or client-side requests
  77.   responseEncoding: 'utf8', // default

  78.   // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  79.   xsrfCookieName: 'XSRF-TOKEN', // default

  80.   // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  81.   xsrfHeaderName: 'X-XSRF-TOKEN', // default

  82.   // `onUploadProgress` allows handling of progress events for uploads
  83.   // browser only
  84.   onUploadProgress: function (progressEvent) {
  85.     // Do whatever you want with the native progress event
  86.   },

  87.   // `onDownloadProgress` allows handling of progress events for downloads
  88.   // browser only
  89.   onDownloadProgress: function (progressEvent) {
  90.     // Do whatever you want with the native progress event
  91.   },

  92.   // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
  93.   maxContentLength: 2000,

  94.   // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
  95.   maxBodyLength: 2000,

  96.   // `validateStatus` defines whether to resolve or reject the promise for a given
  97.   // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  98.   // or `undefined`), the promise will be resolved; otherwise, the promise will be
  99.   // rejected.
  100.   validateStatus: function (status) {
  101.     return status >= 200 && status < 300; // default
  102.   },

  103.   // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  104.   // If set to 0, no redirects will be followed.
  105.   maxRedirects: 21, // default

  106.   // `beforeRedirect` defines a function that will be called before redirect.
  107.   // Use this to adjust the request options upon redirecting,
  108.   // to inspect the latest response headers,
  109.   // or to cancel the request by throwing an error
  110.   // If maxRedirects is set to 0, `beforeRedirect` is not used.
  111.   beforeRedirect: (options, { headers }) => {
  112.     if (options.hostname === "example.com") {
  113.       options.auth = "user:password";
  114.     }
  115.   },

  116.   // `socketPath` defines a UNIX Socket to be used in node.js.
  117.   // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  118.   // Only either `socketPath` or `proxy` can be specified.
  119.   // If both are specified, `socketPath` is used.
  120.   socketPath: null, // default

  121.   // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  122.   // and https requests, respectively, in node.js. This allows options to be added like
  123.   // `keepAlive` that are not enabled by default.
  124.   httpAgent: new http.Agent({ keepAlive: true }),
  125.   httpsAgent: new https.Agent({ keepAlive: true }),

  126.   // `proxy` defines the hostname, port, and protocol of the proxy server.
  127.   // You can also define your proxy using the conventional `http_proxy` and
  128.   // `https_proxy` environment variables. If you are using environment variables
  129.   // for your proxy configuration, you can also define a `no_proxy` environment
  130.   // variable as a comma-separated list of domains that should not be proxied.
  131.   // Use `false` to disable proxies, ignoring environment variables.
  132.   // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  133.   // supplies credentials.
  134.   // This will set an `Proxy-Authorization` header, overwriting any existing
  135.   // `Proxy-Authorization` custom headers you have set using `headers`.
  136.   // If the proxy server uses HTTPS, then you must set the protocol to `https`.
  137.   proxy: {
  138.     protocol: 'https',
  139.     host: '127.0.0.1',
  140.     port: 9000,
  141.     auth: {
  142.       username: 'mikeymike',
  143.       password: 'rapunz3l'
  144.     }
  145.   },

  146.   // `cancelToken` specifies a cancel token that can be used to cancel the request
  147.   // (see Cancellation section below for details)
  148.   cancelToken: new CancelToken(function (cancel) {
  149.   }),

  150.   // an alternative way to cancel Axios requests using AbortController
  151.   signal: new AbortController().signal,

  152.   // `decompress` indicates whether or not the response body should be decompressed
  153.   // automatically. If set to `true` will also remove the 'content-encoding' header
  154.   // from the responses objects of all decompressed responses
  155.   // - Node only (XHR cannot turn off decompression)
  156.   decompress: true // default

  157.   // `insecureHTTPParser` boolean.
  158.   // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
  159.   // This may allow interoperability with non-conformant HTTP implementations.
  160.   // Using the insecure parser should be avoided.
  161.   // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
  162.   // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
  163.   insecureHTTPParser: undefined // default

  164.   // transitional options for backward compatibility that may be removed in the newer versions
  165.   transitional: {
  166.     // silent JSON parsing mode
  167.     // `true`  - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
  168.     // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
  169.     silentJSONParsing: true, // default value for the current Axios version

  170.     // try to parse the response string as JSON even if `responseType` is not 'json'
  171.     forcedJSONParsing: true,
  172.     
  173.     // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
  174.     clarifyTimeoutError: false,
  175.   },

  176.   env: {
  177.     // The FormData class to be used to automatically serialize the payload into a FormData object
  178.     FormData: window?.FormData || global?.FormData
  179.   },

  180.   formSerializer: {
  181.       visitor: (value, key, path, helpers)=> {}; // custom visitor funaction to serrialize form values
  182.       dots: boolean; // use dots instead of brackets format
  183.       metaTokens: boolean; // keep special endings like {} in parameter key
  184.       indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
  185.   }
  186. }
  187. ```

Response Schema


The response for a request contains the following information.

  1. ``` js
  2. {
  3.   // `data` is the response that was provided by the server
  4.   data: {},

  5.   // `status` is the HTTP status code from the server response
  6.   status: 200,

  7.   // `statusText` is the HTTP status message from the server response
  8.   statusText: 'OK',

  9.   // `headers` the HTTP headers that the server responded with
  10.   // All header names are lowercase and can be accessed using the bracket notation.
  11.   // Example: `response.headers['content-type']`
  12.   headers: {},

  13.   // `config` is the config that was provided to `axios` for the request
  14.   config: {},

  15.   // `request` is the request that generated this response
  16.   // It is the last ClientRequest instance in node.js (in redirects)
  17.   // and an XMLHttpRequest instance in the browser
  18.   request: {}
  19. }
  20. ```

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

  1. ``` js
  2. axios.get('/user/12345')
  3.   .then(function (response) {
  4.     console.log(response.data);
  5.     console.log(response.status);
  6.     console.log(response.statusText);
  7.     console.log(response.headers);
  8.     console.log(response.config);
  9.   });
  10. ```

When using catch, or passing a rejection callback as second parameter ofthen, the response will be available through the error object as explained in the Handling Errors section.

Config Defaults


You can specify config defaults that will be applied to every request.

Global axios defaults


  1. ``` js
  2. axios.defaults.baseURL = 'https://api.example.com';

  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.
  5. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

  6. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  7. ```

Custom instance defaults


  1. ``` js
  2. // Set config defaults when creating the instance
  3. const instance = axios.create({
  4.   baseURL: 'https://api.example.com'
  5. });

  6. // Alter defaults after instance has been created
  7. instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  8. ```

Config order of precedence


Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, thendefaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here's an example.

  1. ``` js
  2. // Create an instance using the config defaults provided by the library
  3. // At this point the timeout config value is `0` as is the default for the library
  4. const instance = axios.create();

  5. // Override timeout default for the library
  6. // Now all requests using this instance will wait 2.5 seconds before timing out
  7. instance.defaults.timeout = 2500;

  8. // Override timeout for this request as it's known to take a long time
  9. instance.get('/longRequest', {
  10.   timeout: 5000
  11. });
  12. ```

Interceptors


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

  1. ``` js
  2. // Add a request interceptor
  3. axios.interceptors.request.use(function (config) {
  4.     // Do something before request is sent
  5.     return config;
  6.   }, function (error) {
  7.     // Do something with request error
  8.     return Promise.reject(error);
  9.   });

  10. // Add a response interceptor
  11. axios.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.   });
  20. ```

If you need to remove an interceptor later you can.

  1. ``` js
  2. const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
  3. axios.interceptors.request.eject(myInterceptor);
  4. ```

You can also clear all interceptors for requests or responses.
  1. ``` js
  2. const instance = axios.create();
  3. instance.interceptors.request.use(function () {/*...*/});
  4. instance.interceptors.request.clear(); // Removes interceptors from requests
  5. instance.interceptors.response.use(function () {/*...*/});
  6. instance.interceptors.response.clear(); // Removes interceptors from responses
  7. ```

You can add interceptors to a custom instance of axios.

  1. ``` js
  2. const instance = axios.create();
  3. instance.interceptors.request.use(function () {/*...*/});
  4. ```

When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag
to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.

  1. ``` js
  2. axios.interceptors.request.use(function (config) {
  3.   config.headers.test = 'I am only a header!';
  4.   return config;
  5. }, null, { synchronous: true });
  6. ```

If you want to execute a particular interceptor based on a runtime check,
you can add a runWhen function to the options object. The interceptor will not be executed if and only if the return
of runWhen is false. The function will be called with the config
object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
asynchronous request interceptor that only needs to run at certain times.

  1. ``` js
  2. function onGetCall(config) {
  3.   return config.method === 'get';
  4. }
  5. axios.interceptors.request.use(function (config) {
  6.   config.headers.test = 'special get headers';
  7.   return config;
  8. }, null, { runWhen: onGetCall });
  9. ```

Multiple Interceptors


Given you add multiple response interceptors
and when the response was fulfilled
- then each interceptor is executed
- then they are executed in the order they were added
- then only the last interceptor's result is returned
- then every interceptor receives the result of its predecessor
- and when the fulfillment-interceptor throws
    - then the following fulfillment-interceptor is not called
    - then the following rejection-interceptor is called
    - once caught, another following fulfill-interceptor is called again (just like in a promise chain).
    
Read the interceptor tests for seeing all this in code.

Handling Errors


  1. ``` js
  2. axios.get('/user/12345')
  3.   .catch(function (error) {
  4.     if (error.response) {
  5.       // The request was made and the server responded with a status code
  6.       // that falls out of the range of 2xx
  7.       console.log(error.response.data);
  8.       console.log(error.response.status);
  9.       console.log(error.response.headers);
  10.     } else if (error.request) {
  11.       // The request was made but no response was received
  12.       // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
  13.       // http.ClientRequest in node.js
  14.       console.log(error.request);
  15.     } else {
  16.       // Something happened in setting up the request that triggered an Error
  17.       console.log('Error', error.message);
  18.     }
  19.     console.log(error.config);
  20.   });
  21. ```

Using the validateStatus config option, you can define HTTP code(s) that should throw an error.

  1. ``` js
  2. axios.get('/user/12345', {
  3.   validateStatus: function (status) {
  4.     return status < 500; // Resolve only if the status code is less than 500
  5.   }
  6. })
  7. ```

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

  1. ``` js
  2. axios.get('/user/12345')
  3.   .catch(function (error) {
  4.     console.log(error.toJSON());
  5.   });
  6. ```

Cancellation


AbortController


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

  1. ``` js
  2. const controller = new AbortController();

  3. axios.get('/foo/bar', {
  4.    signal: controller.signal
  5. }).then(function(response) {
  6.    //...
  7. });
  8. // cancel the request
  9. controller.abort()
  10. ```

CancelToken 👎deprecated


You can also cancel a request using a CancelToken.

The axios cancel token API is based on the withdrawn cancelable promises proposal.


This API is deprecated since v0.22.0 and shouldn't be used in new projects


You can create a cancel token using the CancelToken.source factory as shown below:

  1. ``` js
  2. const CancelToken = axios.CancelToken;
  3. const source = CancelToken.source();

  4. axios.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. axios.post('/user/12345', {
  14.   name: 'new name'
  15. }, {
  16.   cancelToken: source.token
  17. })

  18. // cancel the request (the message parameter is optional)
  19. source.cancel('Operation canceled by the user.');
  20. ```

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

  1. ``` js
  2. const CancelToken = axios.CancelToken;
  3. let cancel;

  4. axios.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. // cancel the request
  11. cancel();
  12. ```

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](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) instead, you can use the [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API, which is supported in the vast majority of browsers, and Node starting with v10 (released in 2018).

  1. ``` js
  2. const params = new URLSearchParams({ foo: 'bar' });
  3. params.append('extraparam', 'value');
  4. axios.post('/foo', params);
  5. ```

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](https://github.com/ljharb/qs) library:

  1. ``` js
  2. const qs = require('qs');
  3. axios.post('/foo', qs.stringify({ 'bar': 123 }));
  4. ```

Or in another way (ES6),

  1. ``` js
  2. import qs from 'qs';
  3. const data = { 'bar': 123 };
  4. const options = {
  5.   method: 'POST',
  6.   headers: { 'content-type': 'application/x-www-form-urlencoded' },
  7.   data: qs.stringify(data),
  8.   url,
  9. };
  10. axios(options);
  11. ```

Older Node.js versions


For older Node.js engines, you can use the [querystring](https://nodejs.org/api/querystring.html) module as follows:

  1. ``` js
  2. const querystring = require('querystring');
  3. axios.post('https://something.com/', querystring.stringify({ foo: 'bar' }));
  4. ```

You can also use the [qs](https://github.com/ljharb/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".

  1. ```
  2. const data = {
  3.   x: 1,
  4.   arr: [1, 2, 3],
  5.   arr2: [1, [2], 3],
  6.   users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
  7. };

  8. await axios.postForm('https://postman-echo.com/post', data,
  9.   {headers: {'content-type': 'application/x-www-form-urlencoded'}}
  10. );
  11. ```

The server will handle it as

  1. ``` js
  2.   {
  3.     x: '1',
  4.     'arr[]': [ '1', '2', '3' ],
  5.     'arr2[0]': '1',
  6.     'arr2[1][0]': '2',
  7.     'arr2[2]': '3',
  8.     'arr3[]': [ '1', '2', '3' ],
  9.     'users[0][name]': 'Peter',
  10.     'users[0][surname]': 'griffin',
  11.     'users[1][name]': 'Thomas',
  12.     'users[1][surname]': 'Anderson'
  13.   }
  14. ````

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. ``` js
  2.   var app = express();
  3.   
  4.   app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
  5.   
  6.   app.post('/', function (req, res, next) {
  7.      // echo body as JSON
  8.      res.send(JSON.stringify(req.body));
  9.   });

  10.   server = app.listen(3000);
  11. ```

Using multipart/form-data format


FormData


To send the data as a multipart/formdata you need to pass a formData instance as a payload.
Setting the Content-Type header is not required as Axios guesses it based on the payload type.

  1. ``` js
  2. const formData = new FormData();
  3. formData.append('foo', 'bar');

  4. axios.post('https://httpbin.org/post', formData);
  5. ```
  
In node.js, you can use the [form-data](https://github.com/form-data/form-data) library as follows:

  1. ``` js
  2. const FormData = require('form-data');
  3. const form = new FormData();
  4. form.append('my_field', 'my value');
  5. form.append('my_buffer', new Buffer(10));
  6. form.append('my_file', fs.createReadStream('/foo/bar.jpg'));

  7. axios.post('https://example.com', form)
  8. ```

🆕 Automatic serialization to FormData


Starting from v0.27.0, Axios supports automatic object serialization to a FormData object if the request Content-Type
header is set to multipart/form-data.

The following request will submit the data in a FormData format (Browser & Node.js):

  1. ``` js
  2. import axios from 'axios';

  3. axios.post('https://httpbin.org/post', {x: 1}, {
  4.   headers: {
  5.     'Content-Type': 'multipart/form-data'
  6.   }
  7. }).then(({data})=> console.log(data));
  8. ```

In the node.js build, the ([form-data](https://github.com/form-data/form-data)) polyfill is used by default.

You can overload the FormData class by setting the env.FormData config variable,
but you probably won't need it in most cases:

  1. ``` js
  2. const axios= require('axios');
  3. var FormData = require('form-data');

  4. axios.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));
  9. ```

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:

  1. ``` js
  2. const obj = {
  3.   x: 1,
  4.   arr: [1, 2, 3],
  5.   arr2: [1, [2], 3],
  6.   users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
  7.   'obj2{}': [{x:1}]
  8. };
  9. ```

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

  1. ``` js
  2. const formData= new FormData();
  3. formData.append('x', '1');
  4. formData.append('arr[]', '1');
  5. formData.append('arr[]', '2');
  6. formData.append('arr[]', '3');
  7. formData.append('arr2[0]', '1');
  8. formData.append('arr2[1][0]', '2');
  9. formData.append('arr2[2]', '3');
  10. formData.append('users[0][name]', 'Peter');
  11. formData.append('users[0][surname]', 'Griffin');
  12. formData.append('users[1][name]', 'Thomas');
  13. formData.append('users[1][surname]', 'Anderson');
  14. formData.append('obj2{}', '[{"x":1}]');
  15. ```

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 sumbit a single file

  1. ``` js
  2. await axios.postForm('https://httpbin.org/post', {
  3.   'myVar' : 'foo',
  4.   'file': document.querySelector('#fileInput').files[0]
  5. });
  6. ```

or multiple files as multipart/form-data.

  1. ``` js
  2. await axios.postForm('https://httpbin.org/post', {
  3.   'files[]': document.querySelector('#fileInput').files
  4. });
  5. ```

FileList object can be passed directly:

  1. ``` js
  2. await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
  3. ```

All files will be sent with the same field names: files[].

🆕 HTML Form Posting (browser)


Pass HTML Form element as a payload to submit it as multipart/form-data content.

  1. ``` js
  2. await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
  3. ```

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

  1. ``` js
  2. await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
  3.   headers: {
  4.     'Content-Type': 'application/json'
  5.   }
  6. })
  7. ```

For example, the Form

  1. ``` html
  2. <form id="form">
  3.   <input type="text" name="foo" value="1">
  4.   <input type="text" name="deep.prop" value="2">
  5.   <input type="text" name="deep prop spaced" value="3">
  6.   <input type="text" name="baz" value="4">
  7.   <input type="text" name="baz" value="5">
  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. <input type="submit" value="Save">
  14. </form>
  15. ```

will be submitted as the following JSON object:

  1. ``` js
  2. {
  3.   "foo": "1",
  4.   "deep": {
  5.     "prop": {
  6.       "spaced": "3"
  7.     }
  8.   },
  9.   "baz": [
  10.     "4",
  11.     "5"
  12.   ],
  13.   "user": {
  14.     "age": "value2"
  15.   }
  16. }
  17. ````

Sending Blobs/Files as JSON (base64) is not currently supported.

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.

  1. ```typescript
  2. let user: User = null;
  3. try {
  4.   const { data } = await axios.get('/user?ID=12345');
  5.   user = data.userDetails;
  6. } catch (error) {
  7.   if (axios.isAxiosError(error)) {
  8.     handleAxiosError(error);
  9.   } else {
  10.     handleUnexpectedError(error);
  11.   }
  12. }
  13. ```

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