VUE局部封装axios接口

1.在src目录下新建api文件夹,新建js文件

VUE局部封装axios接口_第1张图片

2.封装axios接口

import axios from "axios";
import router from "../router";
import {Dialog} from "vant";

//请求拦截器
let instance = axios.create({
  baseURL:"https://baby.xmn.top",   //接口所在域名,将会和传递过来的url进行拼接
  timeOut:5000    //过期时间
});

//设置请求拦截
instance.interceptors.request.use(config => {
//判断是否存在token,如果存在将每个页面的header都添加token
  if(localStorage.getItem(sessionStorage.getItem("id")+'_admin_token')){
    config.headers.common['XX-Device-Type']="mobile";
    config.headers.common['XX-Token']=localStorage.getItem(sessionStorage.getItem("id")+'_admin_token')
  }
  return config;
}, error => {
// 请求错误
  return Promise.reject(error);
});

//设置响应拦截
instance.interceptors.response.use(
  response => {
    let that = this;
    if(response.data.code === 10001){
      Dialog.alert({
        message: '您的登录已过期,请重新登录!'
      }).then(() => {
        that.$router.replace('/managerLogin')
      });
    }
    return response;
  },

  error => {  //默认除了2XX之外都为错误
    if(error.response){
      switch(error.response.status){
        case 401:
          this.$store.commit('delToken');
          this.$router.replace({ //跳转到登录页面
            path: '/managerLogin',
            query: { redirect: router.currentRoute.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
          });
      }
    }
    return Promise.reject(error.response);
  }
);

export default {
  post (url, data, contentType) {
    setData(data);
    return instance({
      method: 'post',
      headers:{
        'Content-type': contentType?contentType:'application/json'
      },
      url: url,
      data: data,
    }).catch((error) => {
      console.log(error.message)
    })
  },
  postFile (url, data) {
    return instance({
      method: 'post',
      headers:{
        'Content-type': 'multipart/form-data'
      },
      url: url,
      data: data,
    }).catch((error) => {
      console.log(error.message)
    })
  },
  get (url, params) {
    setData(params);
    return instance({
      method: 'get',
      url: url,
      params: params,
    }).catch((error) => {
      console.log(error.message)
    })
  },
  delete (url, data) {
    setData(data);
    return instance({
      method: 'delete',
      url: url,
      data: data,
    }).catch((error) => {
      console.log(error.message)
    })
  },
  put (url, data) {
    setData(data);
    return instance({
      method: 'put',
      url: url,
      data: data,
    }).catch((error) => {
      console.log(error.message)
    })
  },
}

function setData(data){
  return data;
}

3.在页面引入封装的js文件

import http from "@/api/manager.js";

4.调用接口

//GET方法
http.get('/api/admin/Course/getCourse',{
            course_id :this.id}).then(
          res=>{
            console.log(res)
          }
        )

//POST方法
http.post('/api/admin/Course/getCourse',{
            course_id :this.id}).then(
          res=>{
            console.log(res)
          }
        )

 

你可能感兴趣的:(VUE)