vue使用axios与后端交互超实用的Api文件配置

不多废话,上代码!需要配置如下两个文件,api.js需要新建自行配置。

api.js

import Vue from 'vue'
import axios from 'axios'
import CryptoJS from 'crypto-js'    //加密
Vue.prototype.$ajax = axios;

axios.defaults.baseURL = 'http://接口地址/';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

//登录
export const abacus = {
  login:(callback, data,error) => {
    let request = {
      url: '/otherStaffs/login',       //接口
      method:'post',
      data:data
    };
    ajax(callback, request,error);
  }
};

function ajax (callback, request,error) {
  let token = window.localStorage.getItem('abacus.token');    //获取token
  let api = request.url;
  let version = '1.0.0';
  let device = 'web';
  let timestamp = new Date().getTime();
  let secretKey = CryptoJS.HmacSHA1(device + '\n' + timestamp + '\n' + version,api).toString();
  let authorization = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse((token == null ? '' : token) + ':' + secretKey));
  if(!request.headers){
    request.headers = {};
  }
  request.headers['Authorization-Device'] = device;
  request.headers['Authorization-Version'] = version;
  request.headers['Authorization-Timestamp'] = timestamp;
  request.headers['Authorization'] = authorization;
  if(!request.data){
    request.data = {};
  }
  axios(request)
    .then((result) => {
      allHandle.handleSuccess(result, callback,error);
    })
    .catch((error) => {
      allHandle.handleCatch(error);
    })
}

export const allHandle = {
  handleSuccess () {},
  handleCatch () {}
};

在main.js中 

import * as api from './Api'

Vue.prototype.$api = api;

api.allHandle.handleSuccess = function (response, callback,error) {
  let body = response.data;
  switch (body.event){
    case 'SUCCESS':
      if(callback){
        callback(body.data);
      }
      break;
    case 'ERROR':
      Vue.prototype.$notify.error({
        title: '操作提示',
        message: body.describe
      });
      if(error){
        error(body);
      }
      break;
    case 'EXCEPTION':
      Vue.prototype.$notify.error({
        title: '操作提示',
        message: body.describe
      });
      if(error){
        error(body);
      }
      break;
    case 'UNAUTHORIZED':
      router.push({name:'userLogin'});
      break;
    default:
      Vue.prototype.$notify.error({
        title: '操作提示',
        message: body.describe
      });
  }
};
api.allHandle.handleCatch = function (error) {
  console.log(error);
};

在vue中

methods:{
    getAxios(){
        this.$api.abacus .login(data=>{
            this.tableData = data
        },{
            id:this.id    //传参
        })
    }
}

猜你喜欢

转载自blog.csdn.net/xr510002594/article/details/82712498