Mardanjan / Blog

学习笔记(在issues里),一些小demo的源码在这里,demo在线地址会持续更新
1 stars 0 forks source link

Vue.js: axios的封装 #9

Open Mardanjan opened 4 years ago

Mardanjan commented 4 years ago

当初参考的博客

import axios from 'axios'
import store from '../store/index'
import router from '../router/index'
import { Message } from 'element-ui'

axios.defaults.timeout = 10000

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

axios.defaults.baseURL = 'https://hiweixiao.xinzhibang168.com/admin/api/'

axios.interceptors.request.use(
  config => {
    if (store.getters.getToken) {
      if (!config.headers.token) {
        config.headers.token = store.getters.getToken
      }
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

export function get (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      if (res.data.err === 1) {
        Message({
          message: '您的身份已过期,请登陆',
          type: 'danger'
        })
        router.push('/login')
      } else if (res.data.err === 0) {
        Message({
          message: res.data.msg,
          type: 'success'
        })
        resolve(res.data)
      }
    }).catch(err => {
      reject(err.data)
    })
  })
}

export function post (url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(res => {
        if (res.data.err === 1) {
          Message({
            message: '您的身份已过期,请登陆',
            type: 'danger'
          })
          router.push('/login')
        } if (res.data.err === 0) {
          Message({
            message: res.data.msg,
            type: 'success'
          })
          resolve(res.data)
        } if (res.data.err === '1001') {
          Message({
            message: res.data.msg,
            type: 'danger'
          })
          resolve(res)
        } if (res.data.err === 1001) {
          Message({
            message: res.data.msg,
            type: 'danger'
          })
          resolve(res)
        } else {
          resolve(res)
        }
      })
      .catch(err => {
        reject(err.data)
      })
  })
}