免费做电脑网站,积分商城平台,建网站 备案,个人小程序开发1、axios官网
https://www.axios-http.cn/docs/interceptors
2、安装 npm install axios 3、在onMouunted钩子函数中使用axios来发送请求#xff0c;接受响应 4.出现的问题#xff1a;
#xff08;1#xff09; 但是如果发送请求请求时间过长#xff0c;回出现请求待处…1、axios官网
https://www.axios-http.cn/docs/interceptors
2、安装 npm install axios 3、在onMouunted钩子函数中使用axios来发送请求接受响应 4.出现的问题
1 但是如果发送请求请求时间过长回出现请求待处理的情况用户体验很不好没有画面我们可以加一个loding遮罩层提示用户正在加载中但是如果没个请求都手动添加代码冗余 2 每个请求都要考虑程序报错的情况都需要catch一下处理下异常而且在拿数据时我们后端写了统一返回格式但是前端响应的数据res里我们的数据被一层一层包裹着每次都要一层一层的拿代码冗余 5、解决方法 使用axios的拦截器 新建一个http文件夹新建index.ts文件用于定义请求和响应拦截器在请求和响应拦截器中解决以上问题 import axios from axios
import { ElMessage, ElLoading } from element-plus
const config {baseURL: ,timeout: 30 * 1000,withCredentials: true,
}let loading: any
class Http {myAxios: any;constructor(config: any) {this.myAxios axios.create(config);// 添加请求拦截器this.myAxios.interceptors.request.use(function (config: any) {//在发送请求时加载loading层loading ElLoading.service({lock: true,text: 加载中...,background: rgba(0, 0, 0, 0.7),})return config;}, function (error: any) {// 对请求错误做些什么loading.close()return Promise.reject(error);});// 添加响应拦截器this.myAxios.interceptors.response.use(function (response: any) {//在响应后关闭loading层loading.close()//取出响应的数据进行判断const { code, message, data } response.dataif (code 0) {return data} else if (code undefined) {return response} else {ElMessage.error(message)return Promise.reject(message);}}, function (error: any) {loading.close()return Promise.reject(error);});}getT(url: string, params?: object, data {}): Promiseany {return this.myAxios.get(url, { params, ...data });}postT(url: string, params?: object, data {}): Promiseany {return this.myAxios.post(url, params, data);}putT(url: string, params?: object, data {}): Promiseany {return this.myAxios.put(url, params, data);}deleteT(url: string, params?: object, data {}): Promiseany {return this.myAxios.delete(url, { params, ...data });}}export default new Http(config);
在页面中使用时直接使用用axios封装好的类 结果