Axios的利用以及封装

打印 上一主题 下一主题

主题 1515|帖子 1515|积分 4545

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一、什么是axios

Axios 是一个基于 promise 的 HTTP 库,可以用在欣赏器和 node.js 中。
特性:



  • 从欣赏器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF
axios可以请求的方法:

get:获取数据,请求指定的信息,返回实体对象
post:向指定资源提交数据(比方表单提交或文件上传)
put:更新数据,从客户端向服务器传送的数据代替指定的文档的内容
patch:更新数据,是对put方法的增补,用来对已知资源进行局部更新
delete:请求服务器删除指定的数据
head:获取报文首部
axios中文网|axios API 中文文档 | axios
二、利用axios

安装

1.npm安装
  1. npm install axios
复制代码
2.yarn安装
  1. yarn add axios
复制代码
3.直接引入
  1. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
复制代码
案例

执行get请求

  1.     <script>
  2.         // 为给定 ID 的 user 创建请求
  3.         axios.get('/user?ID=12345')
  4.             // 请求成功
  5.             .then(function (response) {
  6.                 console.log(response);
  7.             })
  8.             // 请求失败
  9.             .catch(function (error) {
  10.                 console.log(error);
  11.             });
  12.         // 上面的请求也可以这样做
  13.         axios.get('/user', {
  14.             params: {
  15.                 ID: 12345
  16.             }
  17.         })
  18.             .then(function (response) {
  19.                 console.log(response);
  20.             })
  21.             .catch(function (error) {
  22.                 console.log(error);
  23.             });
  24.     </script>
复制代码
第一段代码中查询参数ID=12345是直接附加到URL背面的。这种方式简朴直接,但假如你需要动态构建查询字符串,可能会稍显繁琐。
第二段代码中查询参数是通过params属性通报给axios.get方法的。这种方式更加机动,特别是当你需要动态构建查询参数时。Axios会自动将params对象转换成查询字符串,并将其附加到URL背面。
利用 .then() 和 .catch() 方法来处置惩罚请求乐成或失败的情况。
执行post请求

  1. <script>
  2. // post
  3. // 请求体中包含了用户的firstName和lastName信息。
  4.      axios.post('/user', {
  5.           firstName: 'Fred',
  6.           lastName: 'Flintstone'
  7.       })
  8.           .then(function (response) {
  9.               console.log(response);
  10.           })
  11.           .catch(function (error) {
  12.               console.log(error);
  13.           });
  14. </script>
复制代码

  • axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }):这行代码向服务器的/user路径发送一个POST请求,请求体是一个对象,包含firstName和lastName两个属性,值分别为Fred和Flintstone。
  • .then(function (response) { console.log(response); }):这是一个Promise的处置惩罚方法。假如请求乐成,服务器返回响应,这个响应会被通报给.then方法的回调函数。在这个例子中,回调函数简朴地打印出响应。
  • .catch(function (error) { console.log(error); });:这也是一个Promise的处置惩罚方法。假如请求失败,比如网络题目或服务器错误,错误会被通报给.catch方法的回调函数。在这个例子中,回调函数简朴地打印出错误信息。
执行多个并发请求

  1. <script>
  2. // 执行多个并发请求
  3.         function getUserAccount() {
  4.             return axios.get('/user/12345');
  5.         }
  6.         function getUserPermissions() {
  7.             return axios.get('/user/12345/permissions');
  8.         }
  9.         axios.all([getUserAccount(), getUserPermissions()])
  10.             .then(axios.spread(function (acct, perms) {
  11.                 // 两个请求现在都执行完成
  12.             }));
  13. </script>
复制代码
利用了 axios.all 和 axios.spread 来同时处置惩罚两个异步的 Axios GET 请求,并在它们都完成后执行一些操作


  • getUserAccount 和 getUserPermissions 函数分别发起一个 Axios GET 请求来获取用户账户和权限。
  • axios.all 方法接受一个包含两个 Promise 的数组(由 getUserAccount() 和 getUserPermissions() 返回的 Promise)。
  • axios.spread 方法是一个用于处置惩罚 axios.all 返回的结果的实用工具。它将 axios.all 的结果数组展开为单独的参数,并通报给提供的回调函数。
  • 在回调函数中,您可以访问两个请求的响应,并分别处置惩罚它们。
  • .catch 方法用于捕捉并处置惩罚在请求过程中可能发生的任何错误。
axios API

Axios 提供了一个简朴的 API 来发送各种 HTTP 请求,并处置惩罚响应。以下是 Axios API 的一些常用方法和特性:
创建实例:

创建一个 Axios 实例,并设置一些默认的请求参数:
  1. const instance = axios.create({
  2.   baseURL: 'https://some-domain.com/api/',
  3.   timeout: 1000,
  4.   headers: {'X-Custom-Header': 'foobar'}
  5. });
复制代码
发送请求

Axios 提供了以下方法来发送 HTTP 请求:
  1. axios.get(url[, config])
  2. axios.delete(url[, config])
  3. axios.head(url[, config])
  4. axios.options(url[, config])
  5. axios.post(url[, data[, config]])
  6. axios.put(url[, data[, config]])
  7. axios.patch(url[, data[, config]])
复制代码
此中,url 是请求的 URL,data 是作为请求主体被发送的数据,config 是请求的设置选项
请求设置

请求设置可以包含以部属性:


  • url:请求的 URL。
  • method:创建请求时利用的方法(默认是 get)。
  • headers:自界说请求头。
  • params:要与请求一起发送的 URL 参数。
  • data:作为请求主体被发送的数据。
  • timeout:指定请求超时的毫秒数(0 表现无超时时间)。
  • ... 等等。
这些是创建请求时可以用的设置选项。只有 url 是必须的。假如没有指定 method,请求将默认利用 get 方法。
  1. {
  2.    // `url` 是用于请求的服务器 URL
  3.   url: '/user',
  4.   // `method` 是创建请求时使用的方法
  5.   method: 'get', // default
  6.   // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  7.   // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  8.   baseURL: 'https://some-domain.com/api/',
  9.   // `transformRequest` 允许在向服务器发送前,修改请求数据
  10.   // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  11.   // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  12.   transformRequest: [function (data, headers) {
  13.     // 对 data 进行任意转换处理
  14.     return data;
  15.   }],
  16.   // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  17.   transformResponse: [function (data) {
  18.     // 对 data 进行任意转换处理
  19.     return data;
  20.   }],
  21.   // `headers` 是即将被发送的自定义请求头
  22.   headers: {'X-Requested-With': 'XMLHttpRequest'},
  23.   // `params` 是即将与请求一起发送的 URL 参数
  24.   // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  25.   params: {
  26.     ID: 12345
  27.   },
  28.    // `paramsSerializer` 是一个负责 `params` 序列化的函数
  29.   // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  30.   paramsSerializer: function(params) {
  31.     return Qs.stringify(params, {arrayFormat: 'brackets'})
  32.   },
  33.   // `data` 是作为请求主体被发送的数据
  34.   // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
  35.   // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  36.   // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  37.   // - 浏览器专属:FormData, File, Blob
  38.   // - Node 专属: Stream
  39.   data: {
  40.     firstName: 'Fred'
  41.   },
  42.   // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  43.   // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  44.   timeout: 1000,
  45.    // `withCredentials` 表示跨域请求时是否需要使用凭证
  46.   withCredentials: false, // default
  47.   // `adapter` 允许自定义处理请求,以使测试更轻松
  48.   // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
  49.   adapter: function (config) {
  50.     /* ... */
  51.   },
  52. // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  53.   // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  54.   auth: {
  55.     username: 'janedoe',
  56.     password: 's00pers3cret'
  57.   },
  58.    // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  59.   responseType: 'json', // default
  60.   // `responseEncoding` indicates encoding to use for decoding responses
  61.   // Note: Ignored for `responseType` of 'stream' or client-side requests
  62.   responseEncoding: 'utf8', // default
  63.    // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
  64.   xsrfCookieName: 'XSRF-TOKEN', // default
  65.   // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  66.   xsrfHeaderName: 'X-XSRF-TOKEN', // default
  67.    // `onUploadProgress` 允许为上传处理进度事件
  68.   onUploadProgress: function (progressEvent) {
  69.     // Do whatever you want with the native progress event
  70.   },
  71.   // `onDownloadProgress` 允许为下载处理进度事件
  72.   onDownloadProgress: function (progressEvent) {
  73.     // 对原生进度事件的处理
  74.   },
  75.    // `maxContentLength` 定义允许的响应内容的最大尺寸
  76.   maxContentLength: 2000,
  77.   // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
  78.   validateStatus: function (status) {
  79.     return status >= 200 && status < 300; // default
  80.   },
  81.   // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
  82.   // 如果设置为0,将不会 follow 任何重定向
  83.   maxRedirects: 5, // default
  84.   // `socketPath` defines a UNIX Socket to be used in node.js.
  85.   // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  86.   // Only either `socketPath` or `proxy` can be specified.
  87.   // If both are specified, `socketPath` is used.
  88.   socketPath: null, // default
  89.   // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
  90.   // `keepAlive` 默认没有启用
  91.   httpAgent: new http.Agent({ keepAlive: true }),
  92.   httpsAgent: new https.Agent({ keepAlive: true }),
  93.   // 'proxy' 定义代理服务器的主机名称和端口
  94.   // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
  95.   // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
  96.   proxy: {
  97.     host: '127.0.0.1',
  98.     port: 9000,
  99.     auth: {
  100.       username: 'mikeymike',
  101.       password: 'rapunz3l'
  102.     }
  103.   },
  104.   // `cancelToken` 指定用于取消请求的 cancel token
  105.   // (查看后面的 Cancellation 这节了解更多)
  106.   cancelToken: new CancelToken(function (cancel) {
  107.   })
  108. }
复制代码
响应结构

  1. {
  2.   data: {}, // 服务器提供的响应
  3.   status: 200, // 来自服务器响应的 HTTP 状态码
  4.   statusText: 'OK', // HTTP状态信息
  5.   headers: {}, // 服务器响应的头
  6.   config: {}, // 请求的配置信息
  7.   request: {}  // 请求的 XMLHttpRequest 对象 (仅限浏览器)
  8. }
复制代码
并发请求

Axios 提供了 axios.all 方法来同时执行多个请求,并利用 axios.spread 方法来处置惩罚全部请求的响应:
  1. axios.all([axios.get('/user/12345'), axios.get('/user/12345/permissions')])
  2.   .then(axios.spread((user, permissions) => {
  3.     // 两个请求都完成了
  4.   }));
复制代码
拦截器

可以在请求或响应被 then 或 catch 处置惩罚前拦截它们:
  1. // 添加请求拦截器
  2. axios.interceptors.request.use(function (config) {
  3.     // 在发送请求之前做些什么
  4.     return config;
  5.   }, function (error) {
  6.     // 对请求错误做些什么
  7.     return Promise.reject(error);
  8.   });
  9. // 添加响应拦截器
  10. axios.interceptors.response.use(function (response) {
  11.     // 对响应数据做点什么
  12.     return response;
  13.   }, function (error) {
  14.     // 对响应错误做点什么
  15.     return Promise.reject(error);
  16.   });
复制代码
错误处置惩罚

  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.   });
复制代码
三、Axios封装

Axios 封装是一个常见的实践,旨在简化 HTTP 请求的利用,同时保持代码的整洁和可维护性。通过封装 Axios,可以创建自界说的请求函数,处置惩罚错误,设置请求超时,以及添加其他通用的请求设置。
  1. import axios from 'axios';
  2. // 创建 axios 实例
  3. const http = axios.create({
  4.   baseURL: 'https://api.example.com',
  5.   timeout: 10000, // 请求超时时间
  6. });
  7. // 请求拦截器
  8. http.interceptors.request.use(
  9.   (config) => {
  10.     // 在发送请求之前做些什么,比如设置请求头
  11.     config.headers['Content-Type'] = 'application/json';
  12.     // 可以添加更多的请求头或进行其他配置
  13.     return config;
  14.   },
  15.   (error) => {
  16.     // 对请求错误做些什么
  17.     return Promise.reject(error);
  18.   }
  19. );
  20. // 响应拦截器
  21. http.interceptors.response.use(
  22.   (response) => {
  23.     // 对响应数据做点什么
  24.     // 你可以在这里根据状态码或其他条件处理响应
  25.     return response;
  26.   },
  27.   (error) => {
  28.     // 对响应错误做点什么
  29.     // 你可以在这里统一处理错误,比如显示错误信息
  30.     return Promise.reject(error);
  31.   }
  32. );
  33. // 封装 GET 请求
  34. function get(url, params = {}) {
  35.   return http.get(url, { params });
  36. }
  37. // 封装 POST 请求
  38. function post(url, data = {}) {
  39.   return http.post(url, data);
  40. }
  41. // 导出封装好的请求方法
  42. export { get, post };
复制代码
创建了一个 Axios 实例,并设置了根本的 URL 和超时时间。然后,添加了请求和响应拦截器,以便在请求发送之前和响应返回之后执行一些自界说逻辑。最后,封装了 GET 和 POST 请求方法,并导出了这些方法,以便在其他文件中利用。
如今,你可以在应用程序中的任何地方导入并利用这些封装好的请求方法,比方:
  1. import { get, post } from './path/to/axios-wrapper';
  2. get('/users')
  3.   .then((response) => {
  4.     console.log(response.data);
  5.   })
  6.   .catch((error) => {
  7.     console.error(error);
  8.   });
  9. post('/users', { name: 'John Doe', age: 30 })
  10.   .then((response) => {
  11.     console.log(response.data);
  12.   })
  13.   .catch((error) => {
  14.     console.error(error);
  15.   });
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

干翻全岛蛙蛙

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表