title: axios使用说明与二次封装实践
tags:

  • 前端
  • axios
    categories:
  • 前端
    date: 2020-05-12 13:00:00

简单过一遍axios文档,实践封装一个ajax方法。

axios

axios使用说明与二次封装实践 - 图1
axios使用说明与二次封装实践 - 图2
axios使用说明与二次封装实践 - 图3
axios使用说明与二次封装实践 - 图4
axios使用说明与二次封装实践 - 图5
axios使用说明与二次封装实践 - 图6
axios使用说明与二次封装实践 - 图7

适用于浏览器和Nodejs环境的Promise响应方式的HTTP库

特性

  • 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
  • Client side support for protecting against XSRF

浏览器支持情况

axios使用说明与二次封装实践 - 图8 axios使用说明与二次封装实践 - 图9 axios使用说明与二次封装实践 - 图10 axios使用说明与二次封装实践 - 图11 axios使用说明与二次封装实践 - 图12 axios使用说明与二次封装实践 - 图13
Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔ 11 ✔

axios使用说明与二次封装实践 - 图14

安装

Using npm:

  1. $ npm install axios

Using bower:

  1. $ bower install axios

Using yarn:

  1. $ yarn add axios

Using jsDelivr CDN:

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

Using unpkg CDN:

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

示例

note: CommonJS 用例

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

为了获得TypeScript typings的支持(代码提示和自动补全),在使用CommonJS方式导入的时候需要使用require()

  1. const axios = require('axios').default;
  2. // axios.<method> will now provide autocomplete and parameter typings

Performing a GET request

  1. const axios = require('axios');
  2. // Make a request for a user with a given ID
  3. axios.get('/user?ID=12345')
  4. .then(function (response) {
  5. // handle success
  6. console.log(response);
  7. })
  8. .catch(function (error) {
  9. // handle error
  10. console.log(error);
  11. })
  12. .then(function () {
  13. // always executed
  14. });
  15. // Optionally the request above could also be done as
  16. axios.get('/user', {
  17. params: {
  18. ID: 12345
  19. }
  20. })
  21. .then(function (response) {
  22. console.log(response);
  23. })
  24. .catch(function (error) {
  25. console.log(error);
  26. })
  27. .then(function () {
  28. // always executed
  29. });
  30. // Want to use async/await? Add the `async` keyword to your outer function/method.
  31. async function getUser() {
  32. try {
  33. const response = await axios.get('/user?ID=12345');
  34. console.log(response);
  35. } catch (error) {
  36. console.error(error);
  37. }
  38. }

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

  1. function getUserAccount() {
  2. return axios.get('/user/12345');
  3. }
  4. function getUserPermissions() {
  5. return axios.get('/user/12345/permissions');
  6. }
  7. axios.all([getUserAccount(), getUserPermissions()])
  8. .then(axios.spread(function (acct, perms) {
  9. // Both requests are now complete
  10. }));

axios API

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

axios(config)
  1. // Send a POST request
  2. axios({
  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
  2. axios({
  3. method: 'get',
  4. url: 'http://bit.ly/2mTM3nY',
  5. responseType: 'stream'
  6. })
  7. .then(function (response) {
  8. response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  9. });

axios(url[, config])
  1. // Send a GET request (default method)
  2. axios('/user/12345');

Request method aliases

For convenience aliases have been provided for all supported 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

Helper functions for dealing with concurrent requests.

axios.all(iterable)

axios.spread(callback)

Creating an instance

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

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

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

这里有一些发送请求可用的配置参数,除了url参数之外,都是非必填项,没有具体指定的话,默认会发送get请求。

  1. {
  2. // `url` is the server URL that will be used for the request
  3. url: '/user',
  4. // `method` is the request method to be used when making the request
  5. method: 'get', // default
  6. // `baseURL` will be prepended to `url` unless `url` is absolute.
  7. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  8. // to methods of that instance.
  9. baseURL: 'https://some-domain.com/api/',
  10. // `transformRequest` allows changes to the request data before it is sent to the server
  11. // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  12. // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  13. // FormData or Stream
  14. // You may modify the headers object.
  15. transformRequest: [function (data, headers) {
  16. // Do whatever you want to transform the data
  17. return data;
  18. }],
  19. // `transformResponse` allows changes to the response data to be made before
  20. // it is passed to then/catch
  21. transformResponse: [function (data) {
  22. // Do whatever you want to transform the data
  23. return data;
  24. }],
  25. // `headers` are custom headers to be sent
  26. headers: {'X-Requested-With': 'XMLHttpRequest'},
  27. // `params` are the URL parameters to be sent with the request
  28. // Must be a plain object or a URLSearchParams object
  29. params: {
  30. ID: 12345
  31. },
  32. // `paramsSerializer` is an optional function in charge of serializing `params`
  33. // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  34. paramsSerializer: function (params) {
  35. return Qs.stringify(params, {arrayFormat: 'brackets'})
  36. },
  37. // `data` is the data to be sent as the request body
  38. // Only applicable for request methods 'PUT', 'POST', 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. // syntax alternative to send data into the body
  47. // method post
  48. // only the value is sent, not the key
  49. data: 'Country=Brasil&City=Belo Horizonte',
  50. // `timeout` specifies the number of milliseconds before the request times out.
  51. // If the request takes longer than `timeout`, the request will be aborted.
  52. timeout: 1000, // default is `0` (no timeout)
  53. // `withCredentials` indicates whether or not cross-site Access-Control requests
  54. // should be made using credentials
  55. withCredentials: false, // default
  56. // `adapter` allows custom handling of requests which makes testing easier.
  57. // Return a promise and supply a valid response (see lib/adapters/README.md).
  58. adapter: function (config) {
  59. /* ... */
  60. },
  61. // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  62. // This will set an `Authorization` header, overwriting any existing
  63. // `Authorization` custom headers you have set using `headers`.
  64. // Please note that only HTTP Basic auth is configurable through this parameter.
  65. // For Bearer tokens and such, use `Authorization` custom headers instead.
  66. auth: {
  67. username: 'janedoe',
  68. password: 's00pers3cret'
  69. },
  70. // `responseType` indicates the type of data that the server will respond with
  71. // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  72. // browser only: 'blob'
  73. responseType: 'json', // default
  74. // `responseEncoding` indicates encoding to use for decoding responses
  75. // Note: Ignored for `responseType` of 'stream' or client-side requests
  76. responseEncoding: 'utf8', // default
  77. // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  78. xsrfCookieName: 'XSRF-TOKEN', // default
  79. // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  80. xsrfHeaderName: 'X-XSRF-TOKEN', // default
  81. // `onUploadProgress` allows handling of progress events for uploads
  82. // browser only
  83. onUploadProgress: function (progressEvent) {
  84. // Do whatever you want with the native progress event
  85. },
  86. // `onDownloadProgress` allows handling of progress events for downloads
  87. // browser only
  88. onDownloadProgress: function (progressEvent) {
  89. // Do whatever you want with the native progress event
  90. },
  91. // `maxContentLength` defines the max size of the http response content in bytes allowed
  92. maxContentLength: 2000,
  93. // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
  94. maxBodyLength: 2000,
  95. // `validateStatus` defines whether to resolve or reject the promise for a given
  96. // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  97. // or `undefined`), the promise will be resolved; otherwise, the promise will be
  98. // rejected.
  99. validateStatus: function (status) {
  100. return status >= 200 && status < 300; // default
  101. },
  102. // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  103. // If set to 0, no redirects will be followed.
  104. maxRedirects: 5, // default
  105. // `socketPath` defines a UNIX Socket to be used in node.js.
  106. // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  107. // Only either `socketPath` or `proxy` can be specified.
  108. // If both are specified, `socketPath` is used.
  109. socketPath: null, // default
  110. // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  111. // and https requests, respectively, in node.js. This allows options to be added like
  112. // `keepAlive` that are not enabled by default.
  113. httpAgent: new http.Agent({ keepAlive: true }),
  114. httpsAgent: new https.Agent({ keepAlive: true }),
  115. // `proxy` defines the hostname and port of the proxy server.
  116. // You can also define your proxy using the conventional `http_proxy` and
  117. // `https_proxy` environment variables. If you are using environment variables
  118. // for your proxy configuration, you can also define a `no_proxy` environment
  119. // variable as a comma-separated list of domains that should not be proxied.
  120. // Use `false` to disable proxies, ignoring environment variables.
  121. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  122. // supplies credentials.
  123. // This will set an `Proxy-Authorization` header, overwriting any existing
  124. // `Proxy-Authorization` custom headers you have set using `headers`.
  125. proxy: {
  126. host: '127.0.0.1',
  127. port: 9000,
  128. auth: {
  129. username: 'mikeymike',
  130. password: 'rapunz3l'
  131. }
  132. },
  133. // `cancelToken` specifies a cancel token that can be used to cancel the request
  134. // (see Cancellation section below for details)
  135. cancelToken: new CancelToken(function (cancel) {
  136. }),
  137. // `decompress` indicates whether or not the response body should be decompressed
  138. // automatically. If set to `true` will also remove the 'content-encoding' header
  139. // from the responses objects of all decompressed responses
  140. // - Node only (XHR cannot turn off decompression)
  141. decompress: true // default
  142. }

Response Schema

The response for a request contains the following information.

  1. {
  2. // `data` is the response that was provided by the server
  3. data: {},
  4. // `status` is the HTTP status code from the server response
  5. status: 200,
  6. // `statusText` is the HTTP status message from the server response
  7. statusText: 'OK',
  8. // `headers` the HTTP headers that the server responded with
  9. // All header names are lower cased and can be accessed using the bracket notation.
  10. // Example: `response.headers['content-type']`
  11. headers: {},
  12. // `config` is the config that was provided to `axios` for the request
  13. config: {},
  14. // `request` is the request that generated this response
  15. // It is the last ClientRequest instance in node.js (in redirects)
  16. // and an XMLHttpRequest instance in the browser
  17. request: {}
  18. }

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

  1. axios.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.

Config Defaults

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

Global axios defaults

  1. axios.defaults.baseURL = 'https://api.example.com';
  2. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  3. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Custom instance defaults

  1. // Set config defaults when creating the instance
  2. const instance = axios.create({
  3. baseURL: 'https://api.example.com'
  4. });
  5. // Alter defaults after instance has been created
  6. instance.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 library
  3. const instance = axios.create();
  4. // Override timeout default for the library
  5. // Now all requests using this instance will wait 2.5 seconds before timing out
  6. instance.defaults.timeout = 2500;
  7. // Override timeout for this request as it's known to take a long time
  8. instance.get('/longRequest', {
  9. timeout: 5000
  10. });

Interceptors

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

  1. // Add a request interceptor
  2. axios.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. // Add a response interceptor
  10. axios.interceptors.response.use(function (response) {
  11. // Any status code that lie within the range of 2xx cause this function to trigger
  12. // Do something with response data
  13. return response;
  14. }, function (error) {
  15. // Any status codes that falls outside the range of 2xx cause this function to trigger
  16. // Do something with response error
  17. return Promise.reject(error);
  18. });

If you need to remove an interceptor later you can.

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

You can add interceptors to a custom instance of axios.

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

Handling Errors

  1. axios.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 define HTTP code(s) that should throw an error.

  1. axios.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.

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

Cancellation

You can cancel a request using a cancel token.

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

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

  1. const CancelToken = axios.CancelToken;
  2. const source = CancelToken.source();
  3. axios.get('/user/12345', {
  4. cancelToken: source.token
  5. }).catch(function (thrown) {
  6. if (axios.isCancel(thrown)) {
  7. console.log('Request canceled', thrown.message);
  8. } else {
  9. // handle error
  10. }
  11. });
  12. axios.post('/user/12345', {
  13. name: 'new name'
  14. }, {
  15. cancelToken: source.token
  16. })
  17. // cancel the request (the message parameter is optional)
  18. source.cancel('Operation canceled by the user.');

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

  1. const CancelToken = axios.CancelToken;
  2. let cancel;
  3. axios.get('/user/12345', {
  4. cancelToken: new CancelToken(function executor(c) {
  5. // An executor function receives a cancel function as a parameter
  6. cancel = c;
  7. })
  8. });
  9. // cancel the request
  10. cancel();

Note: you can cancel several requests with the same cancel token.

Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

Browser

In a browser, you can use the URLSearchParams API as follows:

  1. const params = new URLSearchParams();
  2. params.append('param1', 'value1');
  3. params.append('param2', 'value2');
  4. axios.post('/foo', params);

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Alternatively, you can encode data using the qs library:

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

Or in another way (ES6),

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

Node.js

Query string

In node.js, you can use the querystring module as follows:

  1. const querystring = require('querystring');
  2. axios.post('http://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 the querystring method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).

Form data

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

  1. const FormData = require('form-data');
  2. const form = new FormData();
  3. form.append('my_field', 'my value');
  4. form.append('my_buffer', new Buffer(10));
  5. form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
  6. axios.post('https://example.com', form, { headers: form.getHeaders() })

Alternatively, use an interceptor:

  1. axios.interceptors.request.use(config => {
  2. if (config.data instanceof FormData) {
  3. Object.assign(config.headers, config.data.getHeaders());
  4. }
  5. return config;
  6. });

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.

  1. import axios from 'axios';
  2. axios.get('/user?ID=12345');

Resources

Credits

axios is heavily inspired by the [axios使用说明与二次封装实践 - 图15http) provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular.

License

MIT