axios封装统一处理请求接口

·  阅读 2346

1、安装axios

npm install axios -S
复制代码

2、main.js引用,全局挂载

import {getRequest, postRequest} from 'common/axios'
// 挂载全局使用的方法
Vue.prototype.getRequest = getRequest;
Vue.prototype.postRequest = postRequest;
复制代码

3、src文件夹下建立common文件夹,创建 axios.js 进行接口请求统一封装

// 注:process.env.API_ROOTd的配置可以参考我的另一篇文章,关于生产测试环境配置

import axios from 'axios';
import { Toast } from 'vant'

// 统一请求路径前缀
let base = '/api';

// 接口环境地址
let API_ROOT = process.env.API_ROOT 

// 超时设定
axios.defaults.timeout = 15000;
// 跨域访问携带cookie
axios.defaults.withCredentials = true

axios.interceptors.request.use(config => {
    return config;
}, err => {
    Toast('请求超时');    
    return Promise.resolve(err);
});

// http response 拦截器
axios.interceptors.response.use(response => {
    const data = response.data;
    // 根据返回的code值来做不同的处理(和后端约定)
    switch (data.code) {
        case 210:
            Toast(data.message);
            break;
        // 错误
        case 500:            
            Toast("联系管理员");
            break;
        default:
            return data;
    }
    return data;
}, (err) => {
    // 返回状态码不为200时候的错误处理
    Toast('连接错误,请重试');
    return Promise.resolve(err);
});

// get 请求
export const getRequest = (url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'get',
        url: `${API_ROOT}${base}${url}`,
        params: params,
        headers: {
            'accessToken': accessToken
        }
    });
};

// post请求
export const postRequest = (url, params) => {
    let accessToken = getStore("accessToken");
    return axios({
        method: 'post',
        url: `${API_ROOT}${base}${url}`,
        data: params,
        transformRequest: [function (data) {
            let ret = '';
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
            }
            ret = ret.substring(0, ret.length - 1);
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'accessToken': accessToken
        }
    });
};

export const putRequest = (url, params) => {
    // let accessToken = getStore("accessToken");
    return axios({
        method: 'put',
        url: `${API_ROOT}${base}${url}`,
        data: params,
        transformRequest: [function (data) {
            let ret = '';
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
            }
            ret = ret.substring(0, ret.length - 1);
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'accessToken': accessToken
        }
    });
};

export const deleteRequest = (url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'delete',
        url: `${API_ROOT}${base}${url}`,
        params: params,
        headers: {
           'accessToken': accessToken
        }
    });
};

/**
 * 无需token验证的请求 避免旧token过期导致请求失败
 * @param {*} url 
 * @param {*} params 
 */
export const getRequestWithNoToken = (url, params) => {
    return axios({
        method: 'get',
        url: `${API_ROOT}${base}${url}`,
        params: params
    });
};
复制代码

4、api文件夹里统一管理接口

// 统一请求路径前缀在commmon/axios.js中修改
import { getRequest, postRequest } from 'common/axios';

// 接口名称
export const _getClolum = (params) => {
    return getRequest('/get/colum', params)
}
// 接口名称
export const _getSave = (params) => {
    return postRequest('/vo/save', params)
}
复制代码

5、具体组件内调用

import { _getSave } from "@/api/public.js";

const data={
    pageNumber:this.pageNumber,
    pageSize:this.pageSize
}
_getSave(data).then(res => {
   if(res.code==200){
     console.log(res)
   } 
});
复制代码
分类:
前端
标签: