编程javaWeb学习Vue

vue中axios的封装

2020-09-23  本文已影响0人  wj_d678

一般在项目中,都会封装axios,会使得请求更加地方便和简洁。

首先,建立一个axios.js文件,引入axios,可以在该文件中,前端做请求拦截相应、请求方式统一处理

import axios from "axios";  //导入axios
import notification from "ant-design-vue/es/notification";//导入组件库的提示框显示信息(本人用的是ant-design-vue组件库)

接下来,创建axios实例

const service = axios.create({
     baseURL: process.env.BASE_URL, // api base_url,
    timeout: 60 * 1000, // 请求超时时间,
    headers: { "Content-Type": "application/json" },
    withCredentials: true,
    crossDomain: true,
});

响应拦截器

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    // 服务器状态码不是200的情况
    error => {
        if (error.response.status) {
            switch (error.response.status) {
                // 401: 未登录
                // 未登录则跳转登录页面,并携带当前页面的路径
                // 在登录成功后返回当前页面,这一步需要在登录页操作。
                case 401:
                    notification.error({
                        message: "请求失败",
                        description: "登录过期,请重新登录"
                    });
                    axios.get('/relog').then(() => {
                        location.href = window.location.origin 
                    })
                    break;
                // 403 token过期
                // 登录过期对用户进行提示
                // 清除本地token和清空vuex中token对象
                // 跳转登录页面
                case 403:
                    notification.error({
                        message: "请求失败",
                        description: "登录过期,请重新登录"
                    });
                    break;
                // 404请求不存在
                case 404:
                    notification.error({
                        message: "请求失败",
                        description: "网络请求不存在"
                    });
                    break;
                // 其他错误,直接抛出错误提示
                default:
                    notification.error({
                        message: "请求失败",
                        description: error.response.data.message
                    });
            }
            return Promise.reject(error.response);
        }
    }
);

分别对四种请求方式进行定义:url就是请求后端的地址,params是前端传给后端的参数


微信截图_20200923142915.png

然后,建一个api文件夹,用来定义接口方法


微信截图_20200923143423.png
最后,就是在页面中调用接口了,在页面中引入接口文件
微信截图_20200923143640.png

直接request.方法名就可以调用接口了


微信截图_20200923143752.png
上一篇 下一篇

猜你喜欢

热点阅读