axios入门(6)—— axios调用后台接口封装
小白浏览:7382020-12-16 16:38:05本文累计收益:0我也要赚钱

axios调用后台接口封装是为方便使用axios进行后台接口调用,避免重复代码。本例封装后主要包含两个文件InterfaceList.js和http.js,InterfaceList.js文件存放请求接口列表,http.js是接口请求代码:

InterfaceList.js代码如下:
const INTERFACE_LIST={
    //获取用户列表
    getSysUserList:{
        method:'',
        url:'/System/SysUserList'
    },
    //后台管理用户登录
    postAdminLogin:{
        method:'post',
        url:'/System/PostAdminLogin'
    },
    //获取菜单列表
    getSysMenuList:{
        method:'post',
        url:'/System/PostGetSysMenuList'
    },
}
export default INTERFACE_LIST

每个接口信息都包括具体请求接口地址及请求方法。

http.js代码如下:
import axios from 'axios'
import interfaceList from './InterfaceList.js'

//循环遍历输出不同的请求方法
let instance = axios.create({
    baseURL: 'https://localhost:44314/api',
    timeout: 1000
})
const Http = {}; //包裹请求方法的容器
//请求格式统一
for (let key in interfaceList) {
    let api = interfaceList[key]; //url
    //async 作用:避免进入回调地狱,等待请求完成继续执行后面代码
    Http[key] = async function(
        params, //请求参数 get:url,put,post,patch(data),delete:url
        isFormData = false, //标识是否是form-data请求
        config = {} //配置参数
    ) {
        let newParams = {};
        //content-type是否是form-data的判断
        if (params && isFormData) {
            newParams = new FormData();
            for (let i in params) {
                newParams.append(i, params[i]);
            }
        } else {
            newParams = params;
        }
        //不同请求的判断
        let response = {} //请求返回值
        if (api.method === 'put' || api.method === 'post' || api.method === 'patch') {
            try {
                response = await instance[api.method](api.url, newParams, config);
            } catch (err) {
                response = err;
            }
        } else if (api.method === 'delete' || api.method === 'get') {
            config.params = newParams;
            try {
                response = await instance[api.method](api.url, config);
            } catch (err) {
                response = err;
            }
        }
        return response; //返回请求响应值
    }
}
//请求拦截器参加
instance.interceptors.request.use(config => {
    //发起请求
    //alert('发起请求!');
    return config;
}, () => {
    alert('请求错误,请稍后重试!');
})
instance.interceptors.response.use(res => {
    return res;
}, (err) => {
    alert(err + '响应错误,请稍后重试!');
})
export default Http;
三,使用方法
submit() {
                 this.$refs.form.validate(async (valid) => {
                    if (valid) {
                        //let res = await this.$Http.postAdminLogin(this.form);
                        //alert(res.data.msg)
                        //存入菜单,渲染菜单
                        let res = await this.$Http.getSysMenuList();
                    } else {
                        console.log('error submit!');
                        return false;
                    }
                })
            }

 

评论列表
发表评论
+ 关注