全局封装 公共接口 headers 里传model参数方法

4 篇文章 0 订阅

这两天遇到一个需求,需要给项目中使用的公共接口,在调用的地方,请求头headers里加一个model 参数。
一开始就在封装接口的地方添加,添加了几个之后,发现太费时费力了,项目中大概将近200 个公共接口,加的时候要仔细加,要精确的找准每一处需要添加的地方,为了不影响其他地方的调用,最好复制封装的接口,不过这个方案被否定了,很多冗余的封装接口着实没有必要。
接着有伙伴提出就对封装公共接口的方法传参,headers 里的model值取当前页面的路由hash,在页面调用的地方把取到的路由hash作为参数传进去。
不过还是很耗时耗力,经过研究,同事给出了一个很好的思路,在全局封装请求的方法里,统一处理,这个方法不仅高效,而且不容易漏加和错加,下面是梳理过程:

1.把公共接口写成一个json文件白名单,我这边在src下面的assets下面新建json文件夹,里面建commonInterface.json
在这里插入图片描述文件内容:

[
  { "url": "/analysis/queryDocumentProcessizeDegreeLineChart" },
  { "url": "/application/queryCopy" },
  { "url": "/attach/download" },
  { "url": "/attach/upload" },
  { "url": "/basBpmUserChange/query" },
  { "url": "/basBpmUserChange/save" },
  { "url": "/bpm/agent/batch-delete" },
  { "url": "/bpm/agent/delete" },
  { "url": "/bpm/agent/query" },
  { "url": "/bpm/agent/save" },
  { "url": "/bpm/collection/quick-query" },
  { "url": "/bpm/createnav/initiate-list" },
  { "url": "/bpm/createnav/query" },
  { "url": "/bpm/linkProject/query" },
  { "url": "/bpm/pass-read/passread" },
  { "url": "/bpm/process/manage/withDrawInstance" },
  { "url": "/bpm/processquery/v2/mySponsor" },
  { "url": "/bpm/processquery/v2/processManage" },
  { "url": "/bpm/processquery/v2/tracking" },
  { "url": "/bpm/processversion/quickQuery" },
  { "url": "/bpm/productRelease/manage/deleteProductReleaseInfo" },
  { "url": "/bpm/urge" },
  { "url": "/businessrule/attribute/quickquery" },
  { "url": "/businessRuleAuth/batchDelete" },
  { "url": "/businessRuleAuth/delete" },
  { "url": "/businessRuleAuth/getAllTree" },
  { "url": "/businessRuleAuth/queryList" },
  { "url": "/businessRuleAuth/saveOrUpdate" },
  { "url": "/businessRuleAuth/updateState" },
  { "url": "/businessRuleManage/dele" },
  { "url": "/businessRuleManage/deleteReplace" },
  { "url": "/businessRuleManage/duplicateRule" },
  { "url": "/businessRuleManage/export-brs" },
  { "url": "/businessRuleManage/exportReplace" },
  { "url": "/businessRuleManage/getBusinessRuleDetail" },
  { "url": "/businessRuleManage/getReplace" },
  { "url": "/businessRuleManage/import-brs" },
  { "url": "/businessRuleManage/preview-brs" },
  { "url": "/businessRuleManage/queryList" },
  { "url": "/businessRuleManage/replace" },
  { "url": "/businessRuleManage/saveBtType" },
  { "url": "/businessRuleManage/saveBusinessRule" },
  { "url": "/datadictionary/getDictionaryOption" },
  { "url": "/datamanage/dataImport" },
  { "url": "/document/print" },
  { "url": "/document-modeling/getCopy" },
  { "url": "/electronicSignature/download" },
  { "url": "/foldertree/deleteCopy" },
  { "url": "/foldertree/saveCopy" },
  { "url": "/mangercenterdoc/uploadCopy" },
  { "url": "/modelapprove/query" },
  { "url": "/modellist/getUserRoleNameCopy" },
  { "url": "/modellist/queryKpiInBase" },
  { "url": "/modellistjson/ZCGetJson" },
  { "url": "/modellistjsonname/query" },
  { "url": "/modelResponsibility/getPosts" },
  { "url": "/modeltree/getTreeNodeWithoutAuthCopy" },
  { "url": "/om/getKpiIndexNum" },
  { "url": "/om/getProcessEfficiency" },
  { "url": "/om/getProcessUtilization" },
  { "url": "/om/getRiskIndexNum" },
  { "url": "/org/info/query" },
  { "url": "/org/manager/findOrgUsers" },
  { "url": "/org/tree/deleteTree" },
  { "url": "/org/tree/getAllRootTree" },
  { "url": "/process/analysis/postAverageTime" },
  { "url": "/processModel/getBusinessRuleAllTree" },
  { "url": "/processModel/getModelTree" },
  { "url": "/processNodeConfig/saveProcessField" },
  { "url": "/processPermissions/delete" },
  { "url": "/processPermissions/deleteList" },
  { "url": "/processPermissions/query" },
  { "url": "/processPermissions/save" },
  { "url": "/regulation/download" },
  { "url": "/regulation/getRegulationFolderCopy" },
  { "url": "/regulation/queryCopy" },
  { "url": "/regulation/queryReleasedCopy" },
  { "url": "/regulation/queryReleasedel" },
  { "url": "/regulation/save2Copy" },
  { "url": "/regulation/upload" },
  { "url": "/repositorybo/getRepositoryboFolder" },
  { "url": "/repositorybo/page" },
  { "url": "/select/user/cqp/getTotalOrgByNameCopy" },
  { "url": "/select/user/cqp/getTotalOrgCopy" },
  { "url": "/service/getHomePegeContent" },
  { "url": "/subjectrule/batchsave" },
  { "url": "/systemAuditManger/getDetailByOrgid" },
  { "url": "/systemChapterRelation/getTree" },
  { "url": "/systemManagement/getHistory" },
  { "url": "/systemManagement/getInterList" },
  { "url": "/test/automatic/batch-delete" },
  { "url": "/test/automatic/delete" },
  { "url": "/test/automatic/query" },
  { "url": "/test/automatic/run-test" },
  { "url": "/test/automatic/test-record-list" },
  { "url": "/vckpi/queryTreeD2D/" },
  { "url": "/frameVersion/getTreeNode" }

]

这里就像一个小型的数据库,里面所有的数据都是公共接口,里面每一个接口在页面很多地方调用2次或多次。
2.接着,在utils文件夹里,新建一个baseFetch.js,作为一个工具函数,里面封装公共接口传参方法:

// 封装 公共接口 headers 里传model参数
import store from '@/store'
// 获取公共接口白名单
const commonInterface=require('../assets/json/commonInterface.json')

const addModelUrl=(currentRequest)=>{
   // 存储当前页面的hash值
   store.commit('app/setCommonInterface', window.location.hash.slice(1))
   // model 公共参数
   let modelInterface=''
   modelInterface=localStorage.getItem('CommonInterface')
   // 前面没有 / 的request.url 处理为/
   let newRequestUrl=currentRequest.url?currentRequest.url:''
   if(newRequestUrl[0]!='/'){
     newRequestUrl='/'+newRequestUrl
   }
   // 请求的接口和公共接口白名单对比
   for (let index = 0; index < commonInterface.length; index++) {
     const element = commonInterface[index];
     if(newRequestUrl.includes(element.url)){
       // 对比上就是公共接口 给headers加model 参数
       currentRequest.headers['model'] =modelInterface?modelInterface:''
     }
   }2

}

export {addModelUrl}

3.补充一点,modelInterface实际上就是取的当前页路由 hash,存到vuex中,也存到localStorage中,vuex的存写法:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
let store = new Vuex.Store({
    // 1. state
    state:{
      commonInterface:localStorage.getItem('CommonInterface')||'',//当前页面的hash
    },
    // 2. mutations
    mutations:{
        // state指的是state的数据
        // payload传递过来的数据
        // 当前页面的hash
    setCommonInterface(state,payload){
      localStorage.setItem('CommonInterface',JSON.stringify(payload))
      state.commonInterface = payload
    		}
    }
});

export default store;

4.在全局封装的请求方法的地方调用:

import { addModelUrl } from '../utils/baseFetch'
service.interceptors.request.use(request => {
  // 调用公共传model 参数方法
  addModelUrl(request)
  localStorage.setItem('baseURL', process.env.VUE_APP_BASE_URL)
  const { id } = store.state.app.userInfo
  const token = localStorage.getItem('sxToken')
  if (token) {
    request.headers.token = token
  }
  if (id) {
    request.headers.Pragma = 'no-cache'
    request.headers['Cache-Control'] = 'no-cache, no-store'
    if (request.method !== 'post') {
      if (!request.params) {
        request.params = {}
      }
    } else {
      if (request.toast === undefined) {
        request.toast = true
      }
      if (!request.data) {
        request.data = {}
      }
    }
  }
  return request
})

在页面的效果:
在这里插入图片描述

这样就加好了,高效准确,很感谢同事的建议,以后自己遇到问题也要多思考,多想想最优方案,让自己成为更好的自己,不断鞭策自己,不断挑战,不断进步~~~~~~~~~

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
封装一个全局请求接口,可以使用 axios 的拦截器来实现。拦截器可以在请求发送前或响应返回后对请求或响应进行处理,可以用来统一处理请求头、响应拦截、错误处理等操作。下面是一个简单的 axios 封装示例: ```javascript // 导入 axios import axios from 'axios' // 创建 axios 实例 const instance = axios.create({ baseURL: 'http://api.example.com', // 设置请求的基础 URL timeout: 5000 // 设置请求超时时间 }) // 请求拦截器 instance.interceptors.request.use( config => { // 在请求发送之前做些什么 // 统一添加请求头信息 config.headers.Authorization = localStorage.getItem('token') return config }, error => { // 请求错误时做些什么 return Promise.reject(error) } ) // 响应拦截器 instance.interceptors.response.use( response => { // 对响应数据做些什么 return response.data }, error => { // 对响应错误做些什么 if (error.response) { // 根据响应状态码进行错误处理 switch (error.response.status) { case 401: // 未登录,跳转到登录页 break case 403: // 没有权限,提示用户 break case 404: // 请求的资源不存在,提示用户 break default: // 其他错误,提示用户 } } return Promise.reject(error) } ) // 导出封装后的 axios 实例 export default instance ``` 这样就可以在项目中使用封装后的 axios 实例,而不用每次都手动配置请求头、错误处理等操作。例如: ```javascript import axios from '@/utils/request' // 发送 GET 请求 axios.get('/users').then(response => { console.log(response) }) // 发送 POST 请求 axios.post('/login', { username: 'admin', password: '123456' }).then(response => { console.log(response) }) ``` 这的 `/users` 和 `/login` 是相对于 `baseURL` 的路径,例如 `http://api.example.com/users`、`http://api.example.com/login`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值