vue封装http请求

import axios from 'axios'
import isObject from 'lodash/isObject'


const http = function (api, data = {}, withoutToken = false) {
    const { url, method } = isObject(api) ? api : { url: api, method: 'post' }
    const accessToken=localStorage.getItem('accessToken')
    const platform='pc'
    const v='2'

    return axios({
        url: withoutToken ? `${url}?platform=${platform}&v=${v}` : `${url}?accessToken=${accessToken}&platform=${platform}&v=${v}`,
        method,
        data,
    }).catch(e => {
        throw new Error('网络异常')
    }).then(res => {
        if(res.data.code===2001||res.data.code===2002){
            this.$confirm(res.data.message[0].details, '鲸保网提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
              }).then(() => {
                this.$router.push({path:'/my/order/list'})
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消'
                });
              });
        }else if (res.data.code === 502) {
            this.$message({
                message: '您现在是未登录状态,请前去登录',
                type: 'warning'
              });
            this.$router.replace({ path: '/login' })
        } else if (res.data.code == 500) {
            throw new Error(res.data.message[0].details)
        }
        return res.data
    })
}

export default http


posted @ 2019-01-08 10:30  李美玲  阅读(4909)  评论(0编辑  收藏  举报