当前位置: 代码网 > it编程>前端脚本>Vue.js > vue3.0(十六)axios详解以及完整封装方法

vue3.0(十六)axios详解以及完整封装方法

2024年07月28日 Vue.js 我要评论
axios详解以及完整封装方法


axios简介

axios与后台进行数据交互, axios 是一个基于 promise 的 http 库,可以用在浏览器和 node.js 中
axios的github
axios 是一个基于 promise 的 http 库,简单的讲就是可以发送get、post等请求,可以用在浏览器和 node.js 中。react等框架的出现,促使了axios轻量级库的出现,因为vue等,不需要操作dom,所以不需要引入jquery.js了。

1. promise

异步编程的一种解决方案

  1. 所谓promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果
  2. promise提供统一的api,各种异步操作都可以用同样的方法进行处理
  3. promise对象代表一个异步操作,有三种状态:pending(进行中)、resolved(已完成,又称fulfilled)和rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态 (英语意思就是“承诺”,表示其他手段无法改变)
  4. 与事件(event)完全不同,事件的特点是,如果你错过了它,再去监听,是得不到结果的。 有了promise对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数

2. axios特性

  1. 从浏览器创建 xmlhttprequests
  2. 从 node.js 创建 http 请求
  3. 支持 promise api
  4. 拦截请求和响应
  5. 转换请求和响应数据
  6. 取消请求
  7. 超时处理
  8. 查询参数序列化支持嵌套项处理
  9. 自动将请求体序列化为:
    • json (application/json)
    • multipart / formdata (multipart/form-data)
    • url encoded form (application/x-www-form-urlencoded)
  10. 将 html form 转换成 json 进行请求
  11. 自动转换json数据
  12. 获取浏览器和 node.js 的请求进度,并提供额外的信息(速度、剩余时间)
  13. 为 node.js 设置带宽限制
  14. 兼容符合规范的 formdata 和 blob(包括 node.js)
  15. 客户端支持防御xsrf

3. 安装

使用 npm:

 npm install axios

使用 bower:

bower install axios

使用 yarn:

yarn add axios

使用 jsdelivr cdn:

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

使用 unpkg cdn:

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

为了直接使用 require 导入预构建的 commonjs 模块(如果您的模块打包器无法自动解析它们),我们提供了以下预构建模块:

const axios = require('axios/dist/browser/axios.cjs'); // browser
const axios = require('axios/dist/node/axios.cjs'); // node

4. 请求方法

  • get:获取数据,请求指定的信息,返回实体对象
  • post:向指定资源提交数据(例如表单提交或文件上传)
  • put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
  • patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
  • delete:请求服务器删除指定的数据
  • head:获取报文首部
  1. post方法
    post请求常用的数据请求格式有三种:

5. 请求方法别名

为了方便起见,axios为所有支持的请求方法提供了别名:

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

6. 浏览器支持情况

firefox、chrome、safari、opera、edge、ie8+

7. 并发请求

并发请求,就是同时进行多个请求,并统一处理返回值。

  • axios.all(iterable):iterable 是一个可以迭代的参数如数组等
  • axios.spread(callback):callback 要等到所有请求都完成才会执行
<template>
  <div class="hello">......</div>
</template>
 
<script>
import axios from "axios";
export default {
  name: "helloworld",
  created() {
    // 并发请求
    // 并发请求用到了axios的两个方法:axios.all('参数是一个数组')、axios.spread('回调函数')
    axios.all([axios.get("/data.json"), axios.get("/city.json")]).then(
      axios.spread((datares, cityres) => {
        console.log(datares, cityres);
      })
    );
  },
};
</script>
<style scoped>
</style

注意:axios.all的参数是请求函数的数组,在对应的回调then中,调用axios.spead对返回值进行处理即可。
并发请求的应用场景:需要同时进行多个请求,并且需要同时处理接口调用的返回值的时候,我们可以使用并发请求。

axios的config的配置信息

1.浏览器控制台相关的请求信息:

  • request url:请求url
  • request method:请求方式
  • status code:状态码
  • status code:304 not modified
  • request header:请求头 ——view parsed模式
  • user-agent:产生请求的浏览器类型。
  • accept:客户端可识别的内容类型列表。
  • host:请求的主机名。
  • query string parameters:查询字符串参数

2.配置方法

配置对象常用的配置项:
这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 get 方法。更多配置项请查看官方文档

{
  // `url` 是用于请求的服务器 url
  url: '/user',

  // `method` 是创建请求时使用的方法
  method: 'get', // 默认值

  // `baseurl` 将自动加在 `url` 前面,除非 `url` 是一个绝对 url。
  // 它可以通过设置一个 `baseurl` 便于为 axios 实例的方法传递相对 url
  baseurl: 'https://some-domain.com/api/',

  // `transformrequest` 允许在向服务器发送前,修改请求数据
  // 它只能用于 'put', 'post' 和 'patch' 这几个请求方法
  // 数组中最后一个函数必须返回一个字符串, 一个buffer实例,arraybuffer,formdata,或 stream
  // 你可以修改请求头。
  transformrequest: [function (data, headers) {
    // 对发送的 data 进行任意转换处理

    return data;
  }],

  // `transformresponse` 在传递给 then/catch 前,允许修改响应数据
  transformresponse: [function (data) {
    // 对接收的 data 进行任意转换处理

    return data;
  }],

  // 自定义请求头
  headers: {'x-requested-with': 'xmlhttprequest'},

  // `params` 是与请求一起发送的 url 参数
  // 必须是一个简单对象或 urlsearchparams 对象
  params: {
    id: 12345
  },

  // `paramsserializer`是可选方法,主要用于序列化`params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsserializer: function (params) {
    return qs.stringify(params, {arrayformat: 'brackets'})
  },

  // `data` 是作为请求体被发送的数据
  // 仅适用 'put', 'post', 'delete 和 'patch' 请求方法
  // 在没有设置 `transformrequest` 时,则必须是以下类型之一:
  // - string, plain object, arraybuffer, arraybufferview, urlsearchparams
  // - 浏览器专属: formdata, file, blob
  // - node 专属: stream, buffer
  data: {
    firstname: 'fred'
  },
  
  // 发送请求体数据的可选语法
  // 请求方式 post
  // 只有 value 会被发送,key 则不会
  data: 'country=brasil&city=belo horizonte',

  // `timeout` 指定请求超时的毫秒数。
  // 如果请求时间超过 `timeout` 的值,则请求会被中断
  timeout: 1000, // 默认值是 `0` (永不超时)

  // `withcredentials` 表示跨域请求时是否需要使用凭证
  withcredentials: false, // default

  // `adapter` 允许自定义处理请求,这使测试更加容易。
  // 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/readme.md)。
  adapter: function (config) {
    /* ... */
  },

  // `auth` http basic auth
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responsetype` 表示浏览器将要响应的数据类型
  // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
  // 浏览器专属:'blob'
  responsetype: 'json', // 默认值

  // `responseencoding` 表示用于解码响应的编码 (node.js 专属)
  // 注意:忽略 `responsetype` 的值为 'stream',或者是客户端请求
  // note: ignored for `responsetype` of 'stream' or client-side requests
  responseencoding: 'utf8', // 默认值

  // `xsrfcookiename` 是 xsrf token 的值,被用作 cookie 的名称
  xsrfcookiename: 'xsrf-token', // 默认值

  // `xsrfheadername` 是带有 xsrf token 值的http 请求头名称
  xsrfheadername: 'x-xsrf-token', // 默认值

  // `onuploadprogress` 允许为上传处理进度事件
  // 浏览器专属
  onuploadprogress: function (progressevent) {
    // 处理原生进度事件
  },

  // `ondownloadprogress` 允许为下载处理进度事件
  // 浏览器专属
  ondownloadprogress: function (progressevent) {
    // 处理原生进度事件
  },

  // `maxcontentlength` 定义了node.js中允许的http响应内容的最大字节数
  maxcontentlength: 2000,

  // `maxbodylength`(仅node)定义允许的http请求内容的最大字节数
  maxbodylength: 2000,

  // `validatestatus` 定义了对于给定的 http状态码是 resolve 还是 reject promise。
  // 如果 `validatestatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
  // 则promise 将会 resolved,否则是 rejected。
  validatestatus: function (status) {
    return status >= 200 && status < 300; // 默认值
  },

  // `maxredirects` 定义了在node.js中要遵循的最大重定向数。
  // 如果设置为0,则不会进行重定向
  maxredirects: 5, // 默认值

  // `socketpath` 定义了在node.js中使用的unix套接字。
  // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
  // 只能指定 `socketpath` 或 `proxy` 。
  // 若都指定,这使用 `socketpath` 。
  socketpath: null, // default

  // `httpagent` and `httpsagent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. this allows options to be added like
  // `keepalive` that are not enabled by default.
  httpagent: new http.agent({ keepalive: true }),
  httpsagent: new https.agent({ keepalive: true }),

  // `proxy` 定义了代理服务器的主机名,端口和协议。
  // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
  // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
  // `auth`表示应使用http basic auth连接到代理,并且提供凭据。
  // 这将设置一个 `proxy-authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `proxy-authorization` 请求头。
  // 如果代理服务器使用 https,则必须设置 protocol 为`https`
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // see https://axios-http.com/zh/docs/cancellation
  canceltoken: new canceltoken(function (cancel) {
  }),

  // `decompress` indicates whether or not the response body should be decompressed 
  // automatically. if set to `true` will also remove the 'content-encoding' header 
  // from the responses objects of all decompressed responses
  // - node only (xhr cannot turn off decompression)
  decompress: true // 默认值

}

3.默认配置

可以设置全局默认配置,是为了避免多种重复配置在不同请求中重复,比如baseurl、timeout等,这里设置baseurl。
全局 axios 默认值

axios.defaults.baseurl = 'https://api.example.com';
axios.defaults.headers.common['authorization'] = auth_token;
axios.defaults.headers.post['content-type'] = 'application/x-www-form-urlencoded';
"""
自定义实例默认值

"""

// 创建实例时配置默认值
const instance = axios.create({
  baseurl: 'https://api.example.com'
});
 
// 创建实例后修改默认值
instance.defaults.headers.common['authorization'] = auth_token;

4.配置的优先级

配置将会按优先级进行合并。它的顺序是:在 lib/defaults.js 中找到的库默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后面的优先级要高于前面的。

5.axios请求响应结果

{
  // `data` 由服务器提供的响应
  data: {},
  // `status` 来自服务器响应的 http 状态码
  status: 200,
  // `statustext` 来自服务器响应的 http 状态信息
  statustext: 'ok',
  // `headers` 是服务器响应头
  // 所有的 header 名称都是小写,而且可以使用方括号语法访问
  // 例如: `response.headers['content-type']`
  headers: {},
  // `config` 是 `axios` 请求的配置信息
  config: {},
  // `request` 是生成此响应的请求
  // 在node.js中它是最后一个clientrequest实例 (in redirects),
  // 在浏览器中则是 xmlhttprequest 实例
  request: {}
}
axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statustext);
    console.log(response.headers);
    console.log(response.config);
  });

axios的拦截器

在请求或响应被 then 或 catch 处理前拦截它们。

1.请求拦截

请求拦截器用于处理请求,并可以在请求发送之前进行一些操作,例如添加认证头,或者取消请求。

// 添加请求拦截器
/*需要拦截请求的原因
  *   1.config中包含了某些不符合服务器要求的信息
  *   2.发送网络请求的时候需要向用户展示一些加载中的图标
  *   3.网站需要登录才能请求资源,也就是需要token才能请求资源*/
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config; //拦截器里一定要记得将拦截的结果处理后返回,否则无法进行数据获取
  }, function (error) {
    // 对请求错误做些什么
    return promise.reject(error);
  });

2.响应拦截

响应拦截器用于处理所有请求的响应,并可以在发送响应之前对其进行错误处理或者进行一些操作。
例如在服务器返回登录状态失效,需要重新登录的时候,跳转到登录页等。

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return promise.reject(error);
  });

3.移除拦截器

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

4.给自定义的 axios 实例添加拦截器。

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

axios取消请求

注意:从 v0.22.0 开始,axios 支持以 fetch api 方式—— abortcontroller 取消请求,canceltoken api被弃用
这里我们两种方法都介绍一下,使用过程中能用 abortcontroller 就尽量别用 canceltoken
abortcontroller

const controller = new abortcontroller();
 
axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// 取消请求
controller.abort()

canceltoken

let source = axios.canceltoken.source();
 
axios.get('/users/12345',{
	canceltoken: source.token
	}).then(res=>{
		console.log(res)
	}).catch(err=>{
		//取消请求后会执行该方法
		console.log(err)
	})
 
//取消请求,参数可选,该参数信息会发送到请求的catch中
source.cancel('取消后的信息');

也可以通过传递一个 executor 函数到 canceltoken 的构造函数来创建一个 cancel token

const canceltoken = axios.canceltoken;
let cancel;
 
axios.get('/user/12345', {
  canceltoken: new canceltoken(function executor(c) {
	// executor 函数接收一个 cancel 函数作为参数
	cancel = c;
  })
});
 
// 取消请求
cancel();

注意: 可以使用同一个 cancel token 或 signal 取消多个请求

axios的封装

request.js文件

import axios from 'axios';
 
// 创建axios实例
const service = axios.create({
  baseurl: process.env.vue_app_base_api, // api的base_url
  timeout: 5000 // 请求超时时间
});
 
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 可以在这里添加请求头等信息
    // 例如:config.headers['authorization'] = 'bearer your-token';
    return config;
  },
  error => {
    // 请求错误处理
    console.log(error); // for debug
    promise.reject(error);
  }
);
 
// 响应拦截器
service.interceptors.response.use(
  response => {
    // 对响应数据做处理,例如只返回data部分
    const res = response.data;
    // 如果返回的状态码为200,说明成功,可以直接返回数据
    if (res.code === 200) {
      return res.data;
    } else {
      // 其他状态码都当作错误处理
      // 可以在这里对不同的错误码进行不同处理
      return promise.reject({
        message: res.message || 'error',
        status: res.code
      });
    }
  },
  error => {
    // 对响应错误做处理
    console.log('err' + error); // for debug
    return promise.reject(error);
  }
);
 
export default service;

创建了一个axios实例,并为这个实例添加了请求拦截器和响应拦截器。请求拦截器用于在请求发送前做一些处理,比如添加token、设置请求头等;响应拦截器用于处理服务器响应,例如根据服务器返回的状态码对数据进行处理。
封装请求接口api文件

import service from '@/utils/request';
 
// 获取用户列表
export function getuserlist(params) {
  return service.get('/user/list', { params: params });
}
 
// 创建用户
export function createuser(data) {
  return service.post('/user/create', data);
}
 
// 更新用户信息
export function updateuser(id, data) {
  return service.put(`/user/update/${id}`, data);
}

在组件中直接引用,传入相应的参数

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com