vue axios封装,统一管理,添加验证

import axios from 'axios';
import { Message } from 'element-ui';
let baseUrl='https://api.admin.nr.junde.co';
axios.defaults.timeout = 5000;
axios.defaults.baseURL ='';
axios.defaults.headers={
  'Content-Type':'application/json; charset=utf-8'
}
//http request 拦截器
axios.interceptors.request.use(
  config => {
    config.data = JSON.stringify(config.data);
    if(localStorage.getItem('Token')){
      let AUTH_TOKEN='jdau '+localStorage.getItem('Token');
      config.headers={
        'Authorization':AUTH_TOKEN,
        'Content-Type':'application/json; charset=utf-8'
      }
   }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {

    if(!response.data.Success){
      Message(response.data.Message)

    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)
export default axios

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url,params={},t){
  return new Promise((resolve,reject) => {
    axios.get(baseUrl+url,{
      params:params
    },t)
    .then(response => {

      resolve(response);
    })
    .catch(err => {
      if(err.response.status&&err.response.status==401){
        // t
        // 
        t.$router.push({path:'/login'});
       //
      }

      reject(err)
    })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url,data,t){
// var data=JSON.stringify(data);
   return new Promise((resolve,reject) => {
     axios.post(baseUrl+url,data,t)
          .then(response => {
            resolve(response);
          },err => {
            if(err.response.status&&err.response.status==401){
              // t
              // 
              t.$router.push({path:'/login'});
             //
            }
            reject(err)
          })
   })
 }

 /**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(baseUrl+url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(baseUrl+url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}
export function urlconcat(url){
  return baseUrl+url;
}

调用方式

import Vue from 'vue';
import {post,get} from '@/components/common/common';
Vue.prototype.$post=post;
Vue.prototype.$get=get;
 this.$get(url,{},that).then((res) => {
 console.log(res)
})

你可能感兴趣的:(vue)