• 【vue】-------------------- 项目接口管理 -----------------【William】


    一、前言

      在vue项目开发过程中,会涉及到很多接口的处理,当项目足够大时,就需要定义规范统一的接口

      声明:此接口管理是我在做项目时封装的,仅供参考!!!

    二、接口管理

      1、在src目录下创建api文件夹

      2、在api文件夹下创建两个文件 config.ts 和 index.ts

      3、在config.ts里引入axios,配置axios

    // 引入相关的依赖包
    import axios from 'axios'
    import qs from 'qs'
    import Vue from 'vue'
    import cookie from '@/cookie'
    import { Loading } from 'element-ui'
    let loadCount = 0
    // 获取系统当前时间
    function getNowDate () {
      let date:any = new Date()
      let year:any = date.getFullYear() //
      let month:any = date.getMonth() + 1 //
      let day:any = date.getDate() //
      let hour:any = date.getHours() //
      let minutes:any = date.getMinutes() //
      let seconds:any = date.getSeconds() //
      let Milliseconds:any = date.getMilliseconds()
      // 给一位数数据前面加 '0'
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (day >= 0 && day <= 9) {
        day = '0' + day
      }
      if (hour >= 0 && hour <= 9) {
        hour = '0' + hour
      }
      if (minutes >= 0 && minutes <= 9) {
        minutes = '0' + minutes
      }
      if (seconds >= 0 && seconds <= 9) {
        seconds = '0' + seconds
      }
      if (Milliseconds >= 0 && Milliseconds <= 9) {
        Milliseconds = '00' + Milliseconds
      } else if (Milliseconds >= 10 && Milliseconds <= 99) {
        Milliseconds = '0' + Milliseconds
      }
      var currentdate = year + month + day + hour + minutes + seconds + Milliseconds
      return currentdate
    }
    // console.log(getNowDate())
    // 生成15位随机数
    function generate () {
      for (var j = 0; j < 10; j++) {
        var randStr = ''
        for (var i = 0; i < 15; i++) {
          var randItem = Math.floor(Math.random() * 10)
          randStr += randItem
        }
        return randStr
      }
    }
    // 默认设置
    axios.defaults.baseURL = '//' + document.domain + ':' + window.location.port
    // axios.defaults.baseURL = '//' + document.domain + ':9098' // 生产 暂时不用
    // axios.defaults.baseURL = '//' + document.domain + ':9098' // 测试
    axios.defaults.timeout = 100000
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
    axios.defaults.transformRequest = data => {
      // allowDots配置:risksList[0][riskType] => risksList[0].riskType  连接符用 “.”
      if ((typeof (data) === 'string') || (data instanceof FormData)) {
        return data
      } else {
        return qs.stringify(data, { allowDots: true })
      }
    }
    axios.defaults.withCredentials = true // 携带cookie信息,保持session的一致性
    // 添加请求拦截器
    axios.interceptors.request.use(function (config) {
        console.log(config, 'config')
      // 在发送请求之前做些什么
      // console.log(Vue);
      // const token = cookie('token')
      const token = '781f0ff6da9b458f91cca61c9b7bc837'
      console.log(cookie('token'), cookie('userName'))
      // console.log('config.data', config.data, 'config.params', config.params, typeof (config.data))
      // var paramsArr = Object.keys(config.params)
      if (config.data) {
        if (typeof (config.data) === 'string') {
          config.data = JSON.parse(config.data)
          config.data.head = {
            // userCde: cookie('userName')
            userCde: 'bjcd',
            cDataSrc: '010000',
            sysTxCode: '',
            sysTxVrsn: '01',
            sysEvtTraceId: generate(),
            sysReqTime: getNowDate()
          }
          config.data = JSON.stringify(config.data)
          config.params = { 'token': token, 'resType': '01' }
        } else if (config.data instanceof FormData) { // 20190724 为了实现ocr识别,给后台服务拼参数
          config.params = Object.assign(config.params, {
            // 'head.userCde': cookie('userName'),
            'head.userCde': 'bjcd',
            'head.cDataSrc': '010000',
            'head.sysTxCode': '',
            'head.sysTxVrsn': '01',
            'head.sysEvtTraceId': generate(),
            'head.sysReqTime': getNowDate(),
            'token': token,
            'resType': '01'
          })
        }
      } else if (config.params.body && config.params.body.LogOut) { // 20190724 专为退出设置
        config.params = { Logout: 'logout', 'token': token, 'resType': '01' }
      }
      loadCount++
      let loading = Loading.service({
        fullscreen: true,
        text: '加载中'
      })
      return config
    }, function (error) {
      // 对请求错误做些什么
      loadCount--
      if (!loadCount) {
        let loading = Loading.service({})
        loading.close() // 关闭加载前,记得重新定义实例
      }
      return Promise.reject(error)
    })
    
    // // 响应拦截器
    axios.interceptors.response.use(response => {
      loadCount--
      if (!loadCount) {
        let loading = Loading.service({})
        loading.close() // 关闭加载前,记得重新定义实例
      }
      return response
    }, error => {
      loadCount--
      if (!loadCount) {
        let loading = Loading.service({})
        loading.close() // 关闭加载前,记得重新定义实例
        Vue.prototype.$GLOBAL.toastTip('系统异常,请稍后重试', '提示', false)
      }
      return Promise.reject(error)
    })
    
    // /**
    //  * 这是一个请求方法
    //  * @param  {string}  method 请求方式
    //  * @param  {string}  url    请求连接
    //  * @param  {object}  params 请求参数
    //  * @return {Promise}        返回 Promise
    //  */
    function reqMethod (method: any, url: string, data: any, params: any) {
      let head = {}
      if (typeof (data) === 'string') {
        head = { 'Content-Type': 'application/json;charset=UTF-8' }
      } else if (data instanceof FormData) {
        head = { 'Content-Type': 'multipart/form-data' }
      } else {
        head = { 'Content-Type': 'application/x-www-form-urlencoded' }
      }
      return new Promise((resolve, reject) => {
        axios({
          method: method.toLowerCase(),
          url: url,
          'data': data,
          'params': params,
          headers: head || {}
        }).then(function (response) {
          // 无token,跳登录页面
          if (response.data.code === 401) {
            window.location.href = response.data.message
          } else {
            resolve(response.data)
          }
          // let loading = Loading.service({})
          // loading.close()
        }).catch(function (error) {
          console.log('Error', error.message)
          // let loading = Loading.service({})
          // loading.close()
          Vue.prototype.$message.error('系统异常,请稍后重试')
          reject(error)
        })
      })
    }
    
    export default reqMethod

    4、在index.ts里引入config.ts

    // 引入请求的配置文件
    import reqMethod from './config'
    
    // 退出
    export const logout = (params: any) => reqMethod('GET', '/visBase', '', params)
    
    // 权限查询接口
    export const getUserCrm = (data: any) => reqMethod('POST', '/visBase/getUserCrm', JSON.stringify(data), '')
    
    // 特约查询
    export const getFixSpec = (data: any) => reqMethod('POST', '/visBase/getFixSpec', JSON.stringify(data), '')

    5、组件中使用

    import * as API from '@/api'
    
    
    export default Vue.extend({
        methods: {
            async getList () {
               let requestObj = {
                   pageInfo: this.pageInfo,
                   body: this.insureForm
               }
               let resultContent = await API.getUserCrm(requestObj)
           console.log(resultContent) } } }
  • 相关阅读:
    转载:AAC编解码概述
    转载:ADTS header
    wcf寄宿在iis上的跨域访问问题【不止是添加跨域文件】
    转 http 分析工具
    时间管理1
    关于silverlight和Wcf分布式部署注意问题(收藏夹)
    c#修改xml文件
    关于在线编辑的异常
    创业文摘5--从程序员转向企业家的10个建议
    silverlight 后台代码生成gridview
  • 原文地址:https://www.cnblogs.com/dongwei1/p/11612750.html
Copyright © 2020-2023  润新知