当前位置:   article > 正文

axios的使用_import * as axios from "axios";

import * as axios from "axios";

Axios基于Promise的HTTP请求客户端,可同时在浏览器和node.js中使用

axios

基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用

功能特性

  • 在浏览器中发送 XMLHttpRequests 请求
  • 在 node.js 中发送 http请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 自动转换 JSON 数据
  • 客户端支持保护安全免受 XSRF 攻击

浏览器支持

Browser Matrix

安装

使用 bower:

$ bower install axios

使用 npm:

$ npm install axios

例子

发送一个 GET 请求

  1. // Make a request for a user with a given ID
  2. axios.get('/user?ID=12345')
  3. .then(function (response) {
  4. console.log(response);
  5. })
  6. .catch(function (response) {
  7. console.log(response);
  8. });
  9. // Optionally the request above could also be done as
  10. axios.get('/user', {
  11. params: {
  12. ID: 12345
  13. }
  14. })
  15. .then(function (response) {
  16. console.log(response);
  17. })
  18. .catch(function (response) {
  19. console.log(response);
  20. });

发送一个 POST 请求

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

发送多个并发请求

  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

可以通过给 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. });
axios(url[, config])
  1. // Sned a GET request (default method)
  2. axios('/user/12345');

请求方法别名

为方便起见,我们为所有支持的请求方法都提供了别名

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

当使用别名方法时, url、 method 和 data 属性不需要在 config 参数里面指定。

并发

处理并发请求的帮助方法

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

创建一个实例

你可以用自定义配置创建一个新的 axios 实例。

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

实例方法

所有可用的实例方法都列在下面了,指定的配置将会和该实例的配置合并。

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

请求配置

下面是可用的请求配置项,只有 url 是必需的。如果没有指定 method ,默认的请求方法是 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', and 'PATCH'
  12. // The last function in the array must return a string or an ArrayBuffer
  13. transformRequest: [function (data) {
  14. // Do whatever you want to transform the data
  15. return data;
  16. }],
  17. // `transformResponse` allows changes to the response data to be made before
  18. // it is passed to then/catch
  19. transformResponse: [function (data) {
  20. // Do whatever you want to transform the data
  21. return data;
  22. }],
  23. // `headers` are custom headers to be sent
  24. headers: {'X-Requested-With': 'XMLHttpRequest'},
  25. // `params` are the URL parameters to be sent with the request
  26. params: {
  27. ID: 12345
  28. },
  29. // `paramsSerializer` is an optional function in charge of serializing `params`
  30. // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  31. paramsSerializer: function(params) {
  32. return Qs.stringify(params, {arrayFormat: 'brackets'})
  33. },
  34. // `data` is the data to be sent as the request body
  35. // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  36. // When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash
  37. data: {
  38. firstName: 'Fred'
  39. },
  40. // `timeout` specifies the number of milliseconds before the request times out.
  41. // If the request takes longer than `timeout`, the request will be aborted.
  42. timeout: 1000,
  43. // `withCredentials` indicates whether or not cross-site Access-Control requests
  44. // should be made using credentials
  45. withCredentials: false, // default
  46. // `adapter` allows custom handling of requests which makes testing easier.
  47. // Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)).
  48. adapter: function (resolve, reject, config) {
  49. /* ... */
  50. },
  51. // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  52. // This will set an `Authorization` header, overwriting any existing
  53. // `Authorization` custom headers you have set using `headers`.
  54. auth: {
  55. username: 'janedoe',
  56. password: 's00pers3cret'
  57. }
  58. // `responseType` indicates the type of data that the server will respond with
  59. // options are 'arraybuffer', 'blob', 'document', 'json', 'text'
  60. responseType: 'json', // default
  61. // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  62. xsrfCookieName: 'XSRF-TOKEN', // default
  63. // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  64. xsrfHeaderName: 'X-XSRF-TOKEN', // default
  65. // `progress` allows handling of progress events for 'POST' and 'PUT uploads'
  66. // as well as 'GET' downloads
  67. progress: function(progressEvent) {
  68. // Do whatever you want with the native progress event
  69. }
  70. }

响应的数据结构

响应的数据包括下面的信息:

  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 headers that the server responded with
  9. headers: {},
  10. // `config` is the config that was provided to `axios` for the request
  11. config: {}
  12. }

当使用 then 或者 catch 时, 你会收到下面的响应:

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

默认配置

你可以为每一个请求指定默认配置。

全局 axios 默认配置

  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';

自定义实例默认配置

  1. // Set config defaults when creating the instance
  2. var 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 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. var instance = axios.create();
  4. // Override timeout default for the library
  5. // Now all requests 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. });

拦截器

你可以在处理 then 或 catch 之前拦截请求和响应

  1. // 添加一个请求拦截器
  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. // 添加一个响应拦截器
  10. axios.interceptors.response.use(function (response) {
  11. // Do something with response data
  12. return response;
  13. }, function (error) {
  14. // Do something with response error
  15. return Promise.reject(error);
  16. });

移除一个拦截器:

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

你可以给一个自定义的 axios 实例添加拦截器:

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

错误处理

  1. axios.get('/user/12345')
  2. .catch(function (response) {
  3. if (response instanceof Error) {
  4. // Something happened in setting up the request that triggered an Error
  5. console.log('Error', response.message);
  6. } else {
  7. // The request was made, but the server responded with a status code
  8. // that falls out of the range of 2xx
  9. console.log(response.data);
  10. console.log(response.status);
  11. console.log(response.headers);
  12. console.log(response.config);
  13. }
  14. });

Promises

axios 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入 polyfill

TypeScript

axios 包含一个 TypeScript 定义

  1. /// <reference path="axios.d.ts" />
  2. import * as axios from 'axios';
  3. axios.get('/user?ID=12345');

Credits

axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular.

License

MIT



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/299732
推荐阅读
相关标签
  

闽ICP备14008679号