axios封装

1.request.js

import axios from 'axios'
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 30 // request timeout
})

// 封装request拦截器
service.interceptors.request.use(
  config => {
    const token = window.localStorage.getItem('Authorization')
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error.data)
  }
)
// 封装response拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.ret === 0) {
      return res
    } else if (res.ret === 1) {
      return Promise.reject(res)
    }
  },
  error => {
    return Promise.reject({
      ret: 1,
      msg: error.message
    })
  }
)

// 封装get方法  url,params
export function get (url, params = {}) {
  return new Promise((resolve, reject) => {
    service.get(url, {
      params: params
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}
// 封装post方法 url,data
export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    service.post(url, data).then(res => {
      if (res) {
        resolve(res.data)
      }
    }).catch(err => {
      reject(err)
    })
  })
}
// 封装put方法 url,data
export function put (url, data = {}) {
  return new Promise((resolve, reject) => {
    service.put(url, data).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}
// 封装delete方法 url,data
export function del (url, data = {}) {
  return new Promise((resolve, reject) => {
    service.delete(url, data).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}
// 封装patch方法 url,data
export function patch (url, data = {}) {
  return new Promise((resolve, reject) => {
    service.patch(url, data).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}
export default {
  get,
  post,
  put,
  del,
  patch
}

2.api.js

axios封装

 

上一篇:pandas读取excel数据问题记录


下一篇:rvm 安装