axios的使用,处理请求和响应,axios拦截器

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.data

            if (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);
        });
    }
    get<T>(url: string, params?: object, data = {}): Promise<any> {
        return this.myAxios.get(url, { params, ...data });
    }

    post<T>(url: string, params?: object, data = {}): Promise<any> {
        return this.myAxios.post(url, params, data);
    }

    put<T>(url: string, params?: object, data = {}): Promise<any> {
        return this.myAxios.put(url, params, data);
    }

    delete<T>(url: string, params?: object, data = {}): Promise<any> {
        return this.myAxios.delete(url, { params, ...data });
    }

}


export default new Http(config);

在页面中使用时,直接使用用axios封装好的类

结果:

相关推荐
LXY2023050412 分钟前
css三角图标
前端·javascript·css
spring_007_99940 分钟前
在uniapp中修改打包路径
前端·uni-app
cheese-liang1 小时前
Excel中Address函数的用法
前端·excel
prince_zxill1 小时前
JavaScript 中的 CSS 与页面响应式设计
前端·javascript·css·前端框架·html
林涧泣1 小时前
【Uniapp-Vue3】获取用户状态栏高度和胶囊按钮高度
前端·vue.js·uni-app
领秀58583 小时前
我问了DeepSeek和ChatGPT关于vue中包含几种watch的问题,它们是这么回答的……
前端·javascript·vue.js
三原3 小时前
vue3实现可以拖动的弹窗组件, 做这个组件可以学习到什么?
前端·javascript·vue.js
16年上任的CTO3 小时前
vue2-mixin的定义与和使用
前端·javascript·vue.js·mixin
呦呦鹿鸣Rzh3 小时前
HTML-表格,表单标签
java·前端·html
柠檬豆腐脑3 小时前
从前端到全栈:搭建Gitlab并实现自动化部署全栈项目
前端·gitlab