简单封装axios api

  • 可以在代码逻辑中写axios请求,处理请求结果,但是随着项目越来越大,代码会很繁琐,不容易维护,所以,可以把一些在所有请求中都要处理的逻辑抽取出来,封装成api方法。比如每次请求中都要判断是否有权限,每次请求都要携带token。
  1. 建一个request.js文件
import axios from 'axios'

// create an axios instance
const service = axios.create({
    // baseURL: process.env.BASE_API, // api的base_url
    // timeout: 5000,
    //headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
    headers: { 'haha': 'kkkkkkkkkkkkkkk' },
    //method: 'get', //一般需要用post
    // request timeout
})

// request interceptor  请求之前的拦截器
service.interceptors.request.use(config => {
    // Do something before request is sent
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// respone interceptor 请求之后异常状态拦截
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.statusCode === 201 || res.statusCode === 400 || res.statusCode === 401 || res.statusCode === 403 || res.statusCode === 404) {
            return Promise.reject('error');
        } else {
            return response.data;
        }
    },
    error => {
        console.log('err' + error)// for debug
        return Promise.reject(error)
    }
)

export default service

2.添加auth.js文件,代码:

//与用户验证相关的方法

export function getToken() {
    //从localstorage获取token
    return localStorage.getItem('token');
}

export function setToken(token) {
    //本地缓存存储token
    localStorage.setItem('token', token);
}

export function removeToken() {
    //本地缓存移除token
    localStorage.removeItem('token');
}

export function getUserId() {
    //从本地缓存中获取userID
    return localStorage.getItem("userid");
}

export function setUserId(userid) {
    //本地缓存存储userId
    localStorage.setItem('userid', userid);
}

export function removeUserId() {
    //本地缓存移除userId
    localStorage.removeItem('userid');
}

3.在store.js中,添加如下:

import Vue from 'vue'
import Vuex from 'vuex'
import { getToken, setToken, removeToken, getUserId, setUserId, removeUserId } from '../Utils/auth.js'

Vue.use(Vuex);

/*访问状态对象--存放变量*/
const state = {
    token: getToken(),
    userId: getUserId(),
}
/*访问触发对象--存放事件*/
const mutations = {
    SET_TOKEN: (state, token) => {
        setToken(token);
        //state.token = token;
        //localStorage.setItem('token', token);
    },
    SET_USER_ID: (state, m) => {
        setUserId(m);
    },

    //用户注销后删除所有本地数据
    LOGOUT: (state) => {
        removeToken();
        removeUserId();
    }
}
export default new Vuex.Store({
    state,
    mutations
})

4.添加testapi.js

import request from './request'
export function getTest(apiRoute) {
    return request({
        url: apiRoute,
        method: 'get',
        params: { "ai": "ai" }
    })
}

5.使用api

//test,testapi
  created: function() {
    var _this = this;
    //test
    getTest("/project/test").then(response => {
      _this.testapi = response.data;
    });
  },

你可能感兴趣的:(简单封装axios api)