axios拦截器+默认参数配置+自定义header设置+错误统一处理

axios拦截器+默认参数配置+自定义header设置+错误统一处理

这份配置文件可完成简单的项目需求,具体配置视项目而定。主要包含:

  • axios拦截器
  • 默认参数配置
  • 自定义header设置
  • 错误统一处理
  • 请求封装
  • api统一管理

axios拦截器(请求拦截器)

Object.assign 如果目标对象中的属性具有相同的键,则属性将被源对象中的属性覆盖。后面的源对象的属性将类似地覆盖前面的源对象的属性。–MDN

// axiosInterceptor.js
// 目录:src目录新建utils目录,用来存放http配置文件以及axios文件和接口统一管理文件
// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    // 默认参数设置:所有接口都必须传的值(比如:userId)
    let defaultParams = {
      userId: store.state.userId;
    };
    // 自定义header信息(比如token)
    config.headers['B-Token'] = store.state.token;
    // 默认值与接口传来的参数进行合并(注:接口参数与默认值不可重复)
    config.data = Object.assign(defaultParams, config.data);
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

axios拦截器(响应拦截器)

// axiosInterceptor.js
// 添加响应拦截器
// 对后端返回值做一些处理
axios.interceptors.response.use(function (res) {
  // 对响应数据做点什么
  // 状态码全部是后端随性而来,哎~所有状态码返回在res.data里面
  // 这里的状态码可根据实际情况来修改

  // 数据正常情况下返回200
  if(res.data.code=='200'){
    return Promise.resolve(res);
  }else {
    // 数据不正常情况下返回(比如:token过期,参数不足)
    // judgeErrorCode详情看errorCode文件
    judgeErrorCode(`code${res.data.code}`, res.data.msg)
    return Promise.reject(res);
  }
}, function (error) {
  // 对响应错误做点什么
  judgeErrorCode(`code${500}`, '未知错误');
  return Promise.reject(error);
});

错误统一处理

多态最根本的作用就是通过把过程化的条件分支语句转化为对象的多态性,从而消除这些条件分支语句 –《JavaScript设计模式与开发实践》

// message.js文件
// 单独对信息提示做了封装,引入message文件
import { errorMess } from './message.js'

import store from '../store';
// 由于不想在每个代码里面判断(懒),所以将判断全部提出来,放在拦截器里面进行判断(code虽然可能一样,但是提示信息不同)
// 代码里面只写成功的返回数据
// 条件过多不考虑条件判断(后期可能还会添加)
// 修改代码往往比增加代码危险很多

const judgeErrorCode = (code, message) => {
  // 判断errorCode[code]是否为一个函数
  if(errorCode[code] instanceof Function){
    // 调用该函数
    errorCode[code](message);
  }
};
const errorCode = {
  // 需要根据状态码的不同进行不同操作
  code201: function(message){
    errorMess(message);
    // console.log('更新失败');
  },
  code202: function(message){
    // console.log('参数不足');
    errorMess(message);
  },
  code203: function(message){
    // console.log('输入错误');
    errorMess(message);
  },
  code400: function(){
    // console.log('token不能为空');
    // 清空本地用户ID,并重新登录
    store.commit('TO_LOGIN');
  },
  code500: function(message){
    // 服务器错误
    errorMess(message);
  },
}
export default judgeErrorCode;

http封装

// http请求封装方式有很多种,但大同小异
export const postRequest = (url,params,headers={'Content-Type': 'application/x-www-form-urlencoded'}) => {
  return axios({
    method: 'post',
    url,
    data: params,
    transformRequest: [function (data) {
      let req = '';
      for (const key in data) {
        req += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) + '&'
      }
      return req;
    }],
    headers,
  })
};

接口统一管理

接口放到一块,便于后期的管理与维护

如何调用

将所有接口放入api对象中,然后将api对象export出去
避免每个涉及到数据请求的文件都引入apis.js文件
main.js文件将apis.js文件引入

// apis.js
import { postRequest, getRequest, filesRequest, jsonRequest } from '../utils/http'

// 用户信息接口(示例)
export const api = {
  // 用户信息接口
  getUserInfoData: params => postRequest('/v1/getUserInfoData', params),
}

// main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { api } from './utils/apis.js'

Vue.config.productionTip = false
Vue.prototype.api = api;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')


结语

前端小白的认知,如果有不对的地方,还望告知进行修改
详细的配置文件可到github查看

猜你喜欢

转载自blog.csdn.net/qq_38867237/article/details/90374209