vue中接口的封装及调用

1.在src下的utils的request里进行接口的封装和拦截请求

import axios from 'axios'
import {
  getRefreshToken,
  getAuthorizationvalid_
} from "@/api/login"
import {
  Message,
  MessageBox
} from 'element-ui'
import store from '@/store'
import Storage from './Storage.js'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 3*60*1000
})

/*被挂起的请求数组*/
let refreshSubscribers = []

/*push所有请求到数组中*/
function subscribeTokenRefresh(cb) {
  refreshSubscribers.push(cb)
}
/*刷新请求(refreshSubscribers数组中的请求得到新的token之后会自执行,用新的token去请求数据)*/
function onRrefreshed(token) {
  refreshSubscribers.map(cb => cb(token))
}
// request拦截器
service.interceptors.request.use(config => {


  if (store.state.UserToken) {
    config.headers.Authorization = 'bearer ' + store.state.UserToken
  } else {
    axios.defaults.headers.common['Authorization'] = ''
  }
  return config
}, error => {
  // Do something with request error
  Message.error({
    showClose: true,
    message: '加载超时'
  })
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.status === 401 || res.status === 40101) {
      MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
      return Promise.reject('error')
    }
    if (res.status === 403) {
      Message({
        message: '当前用户无相关操作权限!',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('error')
    }
    if (res.status === 40001) {
      Message({
        message: '账户或密码错误!',
        type: 'warning'
      })
      return Promise.reject('error')
    }
    if (response.status !== 200 && res.status !== 200) {
      Message({
        showClose: true,
        message: 'tip',
        type: 'error',
        duration: 5 * 1000
      })
    }
    if (response.status == 200 && res.code == '01') {
      let errStr = '请求失败'
      if (res.message) {
        errStr = res.message
      }
      Message({
        showClose: true,
        message: errStr,
        type: 'error',
        duration: 5 * 1000
      })
    }
    if (response.status == 200 && res.code == '07') {
      let errStr = '未查询到数据'
      if (res.message) {
        errStr = res.message
      }
      Message({
        showClose: true,
        message: errStr,
        type: 'error',
        duration: 5 * 1000
      })
    }
    if (response.status == 200 && res.code == '9005') { //关键字段已经存在
      let errStr = '标识数据已存在'
      if (res.message) {
        errStr = res.message
      }
      Message({
        showClose: true,
        message: errStr,
        type: 'error',
        duration: 5 * 1000
      })
      return response
    } else {
      if (response.headers["content-disposition"]) {
        return response
      } else {
        return response.data
      }
    }
  },
  error => {
    if (error && error.response) {
      var refreshToken = {
        refreshToken: store.state.refresh_token
      }
      switch (error.response.status) {
        case 400:
          if (error.response.data.error === 'invalid_grant'&&
            error.request.responseURL.indexOf('oauth/token')<0) {//非登录情况下
            Message.warning({
              showClose: true,
              message: '你没有权限,请联系管理人员'
            })
          }else if (error.response.data.error === 'invalid_grant'&&
            error.request.responseURL.indexOf('refresh_token')>-1) {//刷新resfresh_token
            Message.warning({
              showClose: true,
              message: '权限过期,请重新登录'
            })
            store.commit('LOGIN_OUT')
            window.location.href = '#/login'
            window.location.reload()
          }
          // else{
          //   Message.warning({
          //     message: '无效请求'
          //   })
          // }
          break
        case 401:
          if (error.response.data.error === 'invalid_grant') {
            MessageBox.confirm('权限过期,请重新登录', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          } else if (error.response.data.error === 'invalid_token') { // token 过期 一般12小时
            axios({
              method:'post',
              url:process.env.BASE_API + "/public/valid",
              headers: {
                'Content-Type': 'application/json',//设置请求头请求格式为JSON
                'Authorization': '' //设置token 其中K名要和后端协调好
              },
              params:{}
           }).then((res)=>{
              console.dir('登录报错?')
             console.dir(res)
              if (res.data.code === '01') {
                MessageBox.confirm('授权码失效,请重新登录', '提示', {
                  confirmButtonText: '确定',
                  type: 'warning'
                }).then(() => {
                  store.commit('LOGIN_OUT')
                  window.location.href = '#/login'
                  window.location.reload()
                })
              } else {
                let retry = new Promise((resolve, reject) => {
                  subscribeTokenRefresh((token) => {
                    window.location.reload()
                    /*将请求挂起*/
                    resolve(config)
                  })
                })
                getRefreshToken(refreshToken).then(res => {
                  var access_token = res.data.access_token.trim()
                  Storage.localSet('access_token', access_token)
                  onRrefreshed(res.access_token)
                  return true
                }).catch(function (error) {
                  if (error.response.data.error === 'invalid_grant' && error.response.data.error_description.indexOf('Invalid refresh token') != -1) {
                    store.commit('LOGIN_OUT')
                    window.location.href = '#/login'
                    window.location.reload()
                  }
                })
                return retry
              }
           }).catch(function (error) {
              //如果失败,则跳转到登录页
              store.commit('LOGIN_OUT')
              window.location.href = '#/login'
              window.location.reload()
              console.log(error);
            })
          } else if(error.response.headers['www-authenticate'].indexOf('error="unauthorized"')>-1){//缓存被清空,没有token缓存
            MessageBox.confirm('权限失效,请重新登录', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            }).then(() => {
              store.commit('LOGIN_OUT')
              window.location.href = '#/login'
              window.location.reload()
            })
          }else{//unauthorized
            Message.warning({
              showClose: true,
              message: '你没有权限,请联系管理人员'
            })
          }
          return
        case 403:
          error.message = '拒绝访问'
          break
        case 502:
          error.message = '网关错误'
          store.commit('LOGIN_OUT')
          window.location.href = '#/login'
          window.location.reload()
          break
        case 500:
          if (error.response.data.error) {
            Message.warning({
              message: '网络失败'
            })
          }
          break
        case 404:
          error.message = '请求错误,未找到该资源'
          break
        case 500:
          error.message = '服务器端出错'
          break
      }
    }
    return Promise.reject(error)
  }
)

export default service

2. 标题在src下新建api文件夹,文件夹里新建与pages里相同的目录

在index.js文件里进一步进行接口的传参,配置等

import axios from '@/utils/request'

export const _exportExcel =(obj,options) => { //导出类接口,不用传参
    if(!options){
        options={responseType: 'blob'}
    }
    return axios.post('/WMS/storageReport/exportStorageReportExcel' ,obj,options)
}
// export const _exportMaterialListExcel = (params) => { // 导出下料清单列表
//      return axios({
//             url: '/MES/stockManageReport/exportMaterialListExcel?'+params,
//             method: 'post',
//             headers: {
//                 'Content-Type': 'application/json; application/octet-stream'
//             },
//             responseType: 'blob',
//         })
// }

export const _queryMaterialListPage =(params,obj)=>{
    return axios.post('/MES/stockManageReport/queryMaterialListPage?'+params,obj)//获取信息,分页,查询条件时间
}
export const getTypeList =  params  => {
    return axios.post('/public/selectAll?',params) //不需要给后台传数据,直接拿数据
}

3.在对应的页面进行函数的封装,获取数据,赋值

   //导出
    DownList(){
      _exportExcel({}).then((res) => {
         constant.downloadExcel(res); 
       }).catch(() => {
         this.$message({
           message: '超时',
           type: 'error'
         })
       });
    },

    //获取列表信息,查询
        getMaterialTableList(){
            this.listLoading = true;
            let param ='pageNum='+this.listQuery.pageNum+'&pageSize='+this.listQuery.pageSize+'&sortBy='+this.orderByType+'&orderBy='+this.sortByType
            let obj = this.materialList;
            //obj里面是要查询的条件,相当于filters
            //data里的
            //listQuery: {
            //pageNum: 1,
            //pageSize: 10,
        	},
        	 //orderByType:'requiredQuality',
        	//sortByType:'desc',
            _queryMaterialListPage(param,obj).then((res) => {
                this.listLoading = false; 
                this.dataList=res.data.records;
            }).catch((e) => {
                this.listLoading = false;
                console.log("请求失败")
            });
        },

  //数据
        getMonthData(){
            _getTypeList().then(res=>{
                if(res.code=='00'){
                this.productMonthData=res.data;
                  }
            })
        },
Logo

前往低代码交流专区

更多推荐