• Axios 的介绍(使用和作用)


    Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js

    axios的作用是什么呢?

     axios主要是用于向后台发起请求的,还有在请求中做更多是可控功能。

    axios 特点

    • 从浏览器中创建 XMLHttpRequests
    • 从 node.js 创建 http 请求
    • 支持 Promise API
    • 拦截请求和响应 (就是有interceptor)
    • 转换请求数据和响应数据
    • 取消请求
    • 自动转换 JSON 数据
    • 客户端支持防御 XSRF

    简单介绍一下promise   吧。  (ps:高手写代码用的都是面向对象,所以根本不用这个回调地狱的手法,promise  主要是用来解决异步问题的,由于很多程序员都是同步思考习惯了,异步思起来就挺麻烦,所以代码会出现一套嵌套这一套,当多起来的时候那真的是可以写出一条长龙。先说一个简单应用把,比如图片的预加载,这可以用promise来写,因为图片大小不同,如果一下子全部加载,会出现堵住,第一张图片加载完了之后开始第二张图片加载,promise就是干这个事情的,“你好了没有?好了就到我了”)

    promise是什么:是一个对象用来传递异步操作的信息,它代表了某个未来才会知道结果的事件(通常是一个异步操作),并且这个事件提供统一的api,可供进一步的处理。

    promise的作用:Promise的出现主要是解决地狱回调的问题,比如你需要结果需要请求很多个接口,这些接口的参数需要另外那个的接口返回的数据作为依赖,这样就需要我们一层嵌套一层,但是有了Promise 我们就无需嵌套。

    promise的本质是什么:分离异步数据获取和业务

    ps: 可能大家对interceptor(拦截器)并不是很熟悉,在这里作下介绍,拦截器可以在请求发送前和发送请求后做一些处理。有一张图可以清晰的了解它在一次HTTP请求中做了什么,如下图

    拦截器

    在请求或响应被 then 或 catch 处理前拦截它们(拦截器可以做什么:在请求或者响应时拦截下来进行处理)

    拦截器分为请求拦截器和响应拦截器

    请求拦截器(interceptors.requst)是指可以拦截每次或指定HTTP请求,并可修改配置项。

    响应拦截器(interceptors.response)可以在每次HTTP请求后拦截住每次或指定HTTP请求,并可修改返回结果项。

    移除拦截器

    自定义axios实例添加拦截器

    执行get请求

    1. // 为给定 ID 的 user 创建请求
    2. axios.get('/user?ID=12345')
    3. .then(function (response) {
    4. console.log(response);
    5. })
    6. .catch(function (error) {
    7. console.log(error);
    8. });
    9. // 可选地,上面的请求可以这样做
    10. axios.get('/user', {
    11. params: {
    12. ID: 12345
    13. }
    14. })
    15. .then(function (response) {
    16. console.log(response);
    17. })
    18. .catch(function (error) {
    19. console.log(error);
    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 (error) {
    9. console.log(error);
    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. // 两个请求现在都执行完成
    10. }));

    可以通过向axios传递相关的配置来创建请求
    axios(config

    1. // 发送 POST 请求
    2. axios({
    3. method: 'post',
    4. url: '/user/12345',
    5. data: {
    6. firstName: 'Fred',
    7. lastName: 'Flintstone'
    8. }
    9. });

    axios(url[,config])

    1. // 发送 GET 请求(默认的方法)
    2. axios('/user/12345');

    axios提供了一下几种请求方式

    1. 1.axios.get(url[, config]) 执行 GET 请求
    2. //eg:
    3. // 向具有指定ID的用户发出请求
    4. axios.get('/user?ID=12345')
    5. .then(function (response) {
    6. console.log(response);
    7. })
    8. .catch(function (error) {
    9. console.log(error);
    10. });
    11. // 也可以通过 params 对象传递参数
    12. axios.get('/user', {
    13. params: {
    14. ID: 12345
    15. }
    16. })
    17. .then(function (response) {
    18. console.log(response);
    19. })
    20. .catch(function (error) {
    21. console.log(error);
    22. });
    23. 2.axios.post(url[, data[, config]]) 执行 POST 请求
    24. //eg:
    25. axios.post('/user', {
    26. firstName: 'Fred',
    27. lastName: 'Flintstone'
    28. })
    29. .then(function (response) {
    30. console.log(response);
    31. })
    32. .catch(function (error) {
    33. console.log(error);
    34. });
    35. 3.axios.request(config)
    36. 4.axios.head(url[, config])
    37. 5.axios.delete(url[, config])
    38. 6.axios.put(url[, data[, config]])
    39. 7.axios.patch(url[, data[, config]])
    40. 8.axios.all(iterable)执行多个并发请求
    41. eg:
    42. function getUserAccount() {
    43. return axios.get('/user/12345');
    44. }
    45. function getUserPermissions() {
    46. return axios.get('/user/12345/permissions');
    47. }
    48. axios.all([getUserAccount(), getUserPermissions()])
    49. .then(axios.spread(function (acct, perms) {
    50. // 两个请求现在都执行完成
    51. }));
    52. 9.axios.spread(callback)
    53. //注意:处理并发请求的助手函数
    54. axios.all(iterable)
    55. axios.spread(callback)

     请求配置

    这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 get 方法。

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

    响应结构

    某个请求的响应包含以下信息

    1. {
    2. // `data` 由服务器提供的响应
    3. data: {},
    4. // `status` 来自服务器响应的 HTTP 状态码
    5. status: 200,
    6. // `statusText` 来自服务器响应的 HTTP 状态信息
    7. statusText: 'OK',
    8. // `headers` 服务器响应的头
    9. headers: {},
    10. // `config` 是为请求提供的配置信息
    11. config: {}
    12. }

    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. // 两个请求现在都执行完成
    10. }));
  • 相关阅读:
    HTML小游戏9 —— 潜行游戏《侠盗罗宾汉》(附完整源码)
    .NET性能优化-使用ValueStringBuilder拼接字符串
    鸿蒙Next-Scroll滚动
    kubeadm部署k8sv1.24使用cri-docker做为CRI
    AWS DAS认证考点整理(Athena&Glue篇)
    flutter开发实战-hero动画简单实现
    (3DV 2017) SEGCloud: Semantic Segmentation of 3D Point Clouds
    phpstudy本地域名伪静态
    在网络层怎样防御入侵行为?
    泰山OFFICE技术讲座:同一行不同字号的字如何对齐绘制
  • 原文地址:https://blog.csdn.net/qq_41872328/article/details/132998259