vue+axios+拦截器+token的接口封装+vue-router

一 项目结构

vue+axios+拦截器+token的接口封装+vue-router_第1张图片

二 API.js(class类枚举了post和get接口)

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//manager/password', params)
    }


    //文章列表
    getArticleList(params) {
        return axios.post('/crms/summary/list', params, config)
    }

   
   

    //================== POST  ==============
    //销售总计
    salesStatistics(params) {
        return axios.get('/crms/product/sale/province/' + params.province + '/city/' + params.city + '/area/' + params.area + '/school/' + params.school + '/stime/' + params.stime + '/etime/' + params.etime + '/total', config)
    }

  

    //======================================   GET  =====================================
// http request 拦截器
axios.interceptors.request.use(
    config => {
        if (localStorage.token) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
            config.headers['authorization'] = 'authorization' + localStorage.token;
        }
        return config
    },
    err => {
        return Promise.reject(err)
    })


// 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

axios.interceptors.request.use和axios.interceptors.response.use为请求和返回拦截器 post和get请求时会在header加上authorization,注意axios post请求默认'Content-Type': 'application/x-www-form-urlencoded',后台需要这种格式需要处理,所以每个接口都有第三个参数config。

三  config.js

let API_ROOT;
if (process.env.NODE_ENV === 'dev') { API_ROOT = '/airbus' }
else if (process.env.NODE_ENV === 'production') { API_ROOT = 'https://manager.airbus.com' }
else if (process.env.NODE_ENV === 'pre') { API_ROOT = 'http://managerpre.airbus.com' }
else if (process.env.NODE_ENV === 'qa') { API_ROOT = 'http://managerqa.airbus.com' }
else if (process.env.NODE_ENV === 'english') { API_ROOT = 'http://managerengdev.airbus.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模块可以自己研究一下,https://mp.csdn.net/postedit/88608683,process.env属性返回一个包含用户环境信息的对象,为全局的,用来判断开发环境。

四 内部接口请求用async...awiat

            async getUserList() {
                try {
                  this.loading = true;
                  let params = {},
                       school_data = {
                        page: this.currentPage,
                        size: 10,
                        phone: this.searchAccount,
                        status: this.searchAccountStatus,
                        userName: this.searchAccountName
                    };
                    params.userRole_param = JSON.stringify(school_data);
                    const response = await api.getUserList(params);
                    [this.listData, this.totalPage] = [ response.content, response.total ];
                } catch(e){
                    console.log(e)
                }finally {
                    this.loading = false;
                }
            },

try请求catch监听异常,finally最后一定会执行。

 

 

你可能感兴趣的:(vue)