axios封装

main.js代码片段如下:

import Axios from 'axios';

const axios = Axios.create({
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    },
    timeout: 1000 * 60 * 60,
});
axios.defaults.withCredentials = true
Vue.prototype.$axios = axios;

//请求拦截
axios.interceptors.request.use(config => {
    let token = localStorage.getItem("userToken") ? JSON.parse(localStorage.getItem("userToken")) : null;
    token && config.headers.token = token;
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截
axios.interceptors.response.use(responce => {
    return responce;
}, error => {
    //错误提醒
    return Promise.reject(error);
});

reqUtil.js位置如下:
axios封装_第1张图片

reqUtil.js代码如下:

执行post请求

/**
 * 执行post请求
 * @param urlObj 可直接是url字符串 如果是字符串
 *         url, errorMsg, successMsg = false
 *         将errorMsg 与 successMsg 设为假值 则设置为不展示错误信息
 * @param data
 * @param config   里面的data 会合并到data,优先级比较低
 * @returns {Promise<*>}
 */
export async function post(urlObj, data = {}, config = {}) {
    if (typeof urlObj === 'string') {
        urlObj = { url: urlObj };
    }
    let { url, errorMsg, successMsg ,code ,settings } = urlObj;
    let mergedConfig = Object.assign({}, config, {
        url,
        method: 'post',
        data
    });
    if (config.data) {
        mergedConfig.data = Object.assign({}, config.data, data);
    }
    return await request( mergedConfig, errorMsg, successMsg , code ,settings );
}

执行get请求:


/**
 * 执行get请求
 * @param urlObj 可直接是url字符串 如果是字符串
 *         url, errorMsg, successMsg = false
 *         将errorMsg 与 successMsg 设为假值 则设置为不展示错误信息
 * @param params
 * @param config   里面的params 会合并到params,优先级比较低
 * @returns {Promise<*>}
 */
export async function get(urlObj, params = {}, config = {}) {
    if (typeof urlObj === 'string') {
        urlObj = { url: urlObj };
    }
    let { url, errorMsg, successMsg , code ,settings } = urlObj;
    let mergedConfig = Object.assign({}, config, {
        url,
        method: 'get',
        params
    });
    if (config.params) {
        mergedConfig.params = Object.assign({}, config.params, params);
    }
    return await request( mergedConfig, errorMsg, successMsg , code ,settings );
}

通用的请求方法:

let $axios = Vue.prototype.$axios;
/**
 * 通用的请求方法
 * 对错误进行消息展示 默认会展示错误信息
 * 如果指定成功信息,展示成功信息
 * 返回data
 * @param config
 * @param errorMsg
 * @param successMsg 设置为true则直接展示后台返回的信息
 * @param code
 * @param settings
 * @returns {Promise<*>}
 */
export async function request(config, errorMsg = '请求服务异常, 未知错误', successMsg = false , code = 0 , settings ) {
    let result = await $axios.request(config).catch((error) => {
        if(settings) settings.loading = false;
        let msg = '服务器异常,请联系管理员';
        return {data: {msg: msg , status : 1}};
    }) , data = result.data;
    if(settings) setTimeout(()=> {  settings.loading = false; },500);
    //判断是否登录可以放这里
    ......
    ......

    if (errorMsg && data.status !== code && errorMsg !== data.msg) {
        Message.error(data.msg || errorMsg);
    }
    if (successMsg && data.status === code) {
        if (successMsg === true) {
            Message.success(data.msg || '操作成功');
        } else {
            Message.success(successMsg);
        }
    }
    return result;
}

api.js

```javascript
import * as reqUtil from '@/api/reqUtil'
/*
*  登录
 * @param objCode , password
* */
export async function login(username , passward , settings) {
    return await reqUtil.get({
        url: '/login' ,
        settings : settings
    },{username , passward} , {withCredentials: true});
}

/**
 * 获取树
 * @param {*} param0
 */
export async function getTree({Id, settings}) {
    return await reqUtil.post({
        url: '/getTree',
        settings
    }, {Id});
}

调用方法

import apifrom "@/services/api";

this.settings.loading = true; //刷新
api.getTree({Id: '123' ,settings}).then(res=>{
	
});

你可能感兴趣的:(javascript,前端)