axios 封装

request.js

import axios from 'axios'
// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 判断是否是提交文件,还是常规请求
    if (config.data instanceof FormData) {
      config.headers = {
        'Content-Type': 'multipart/form-data' // 此处格式自定义
      }
    } else {
      config.data = JSON.stringify(config.data)
      config.headers = {
        'Content-Type': 'application/json', // 此处格式自定义
        token: getLocalStorage('token')
      }
    }
    config.withCredentials = true
    config.timeout = 5000    // 超时时间
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
axios.interceptors.response.use(
  res => {
    let data = res.data
    if (res.statusCode !== 200) {
      if (data.failureReason === 4011 || data.failureReason === 4012) {
        console.log('需要重新登录')
      }
    } else {
      if (data.resultStates === 0) {
        return data
      } else {
        return Promise.reject(data)
      }
    }
  },
  error => {
    notification['error']({
      message: '提示',
      duration: 2,
      description: '后台报错'
    })
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

// 封装get,post
export function get (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params
      })
      .then(response => {
        if (response.success) {
          resolve(response.data)
        }
      })
      .catch(err => {
        reject(err)
      })
  })
}
 
/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data).then(
      response => {
        if (response.success) {
          resolve(response.data)
        }
      },
      err => {
        reject(err)
      }
    )
  })
}

api.js

import { get, post } from './axios'
const api = {
     reqLogin: p => post('api/user/addFormId', p),
      reqGetInfo: p => post('api/user/addFormId', p)
}
export default api
 
// 将 api 引入到 main.js 中
Vue.prototype.$api = api
 
// 这样页面中使用
this.$api.reqLogin().then(res => {
      console.log(res)
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值