vue项目基于axios接口封装

一 文件目录
vue项目基于axios接口封装_第1张图片

1 API.js文件

import axios from 'axios'
import {config, publicUrl} from './config'
import Cookies from 'js-cookie';
import vue from 'vue';

class API {
    // 登录接口
    login(params) {
        return axios.post(publicUrl + '/crms/login/v1/manager/password', params)
    }
    //销售总计
    salesStatistics(params) {
        return axios.get('/crms/product/v1/sale/province/' + params.province + '/city/' + 
        params.city + '/area/' + params.area + '/school/' + params.school + '/stime/' + 
        params.stime + '/etime/' + params.etime + '/total', config)
    }
}

// http response 拦截器
axios.interceptors.response.use(
    response => {
        if (response.data.code !== 200) {
            vue.prototype.$Message.error(response.data.message);
            if (response.data.code === 91000 || response.data.code === 91001 || response.data.code === 91002) {
                localStorage.clear();
                setTimeout(() => window.location.href = '#/login.html',2000)
            }
            return Promise.reject(response)
        }
        return Promise.resolve(response.data.data)
    },
    error => {
        return Promise.reject(error)
    })


export default API

封装了post和get请求的接口,加入了http response拦截器,状态码是和后端约定好的。

二 config.js文件夹

import Qs from 'qs'

let API_ROOT;
if (process.env.NODE_ENV === 'dev') { API_ROOT = '/nf' }
else if (process.env.NODE_ENV === 'production') { API_ROOT = 'https://manager.nf.com' }
else if (process.env.NODE_ENV === 'pre') { API_ROOT = 'http://managerpre.nf.com' }
else if (process.env.NODE_ENV === 'qa') { API_ROOT = 'http://managerqa.nf.com' }
else if (process.env.NODE_ENV === 'test') { API_ROOT = 'http://managerdev.nf.com' }
else if (process.env.NODE_ENV === 'english') { API_ROOT = 'http://managerengdev.nf.com' }

export const config = {
    baseURL: API_ROOT,
    transformRequest: [function (data) {
        data.params = JSON.stringify(data.params)
        data = Qs.stringify(data)
        return data
    }],
    transformResponse: [function (data) { return data }],
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    params: {},
    paramsSerializer: function (params) { return Qs.stringify(params) },
    data: {},
    timeout: 100000,
    withCredentials: false,
    responseType: 'json',
    maxContentLength: 20000,
    validateStatus: function (status) { return status >= 200 && status < 300 },
    maxRedirects: 5000
}

export const publicUrl = API_ROOT;

上面配置了若干环境,供测试,开发,生产使用。(后续会介绍qs模块)

你可能感兴趣的:(vue项目基于axios接口封装)