2020-05-17(vue项目中axios请求和拦截封装)

1. 在src下新建文件夹config/setting.js
module.exports = {
    errorCode: 500,
    invalidCode: 402,
    successCode: 200,
    noPermissionCode: 401,
    messageDuration: 2000,
    requestTimeout: 8000,
    tokenName: "accessToken"
    //  如果有其他需要, 可以设置其他的值
}
2. 在src下utils新建request.js
import axios from "axios";
import {
  errorCode,
  invalidCode,
  messageDuration,
  noPermissionCode,
  requestTimeout,
  successCode,
  tokenName,
} from "@/config/settings";
import { Loading, Message } from "element-ui";
import store from "@/store";
//  nodejs的qs模块
import qs from "qs";
import router from "@/router";

//  先设置基础路由, 超时时间, 请求头类型
const service = axios.create({
  //  全局变量
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: requestTimeout,
  headers: {
     //  一般为"application/json"
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", //这里是个坑哦,后端数据接收方式走的是application/x-www-form-urlencoded;charset=UTF-8,大多数公司可能接收方式不是这种
  },
});

//  设置加载实例
let loadingInstance;
//  请求拦截器, 两个参数, 为两个回调函数, 两个回调函数的默认参数是config设置参数和error请求参数
service.interceptors.request.use(
  (config) => {
  	//  如果存在token的话
    if (store.getters.accessToken) {
      // 携带token
      config.headers[tokenName] = store.getters.accessToken;
    }
    //RSA加密不走qs转义,默认传json给后端
    if (process.env.NODE_ENV !== "test") {
      //这里是个坑哦,后端数据接收方式走的是application/x-www-form-urlencoded;charset=UTF-8,大多数公司可能接收方式不是这种
      //  注意这个config.data.params是什么
      if (config.data && !config.data.param) {
        console.log(config); //  注意这里的config携带哪些东西
        //  将config.data转成x-www-form-urlencoded这种类型
        config.data = qs.stringify(config.data);
      }
    }

    //  如果有对应的方法的话, 加载
    if (
      config.url.includes("add") ||
      config.url.includes("edit") ||
      config.url.includes("set") ||
      config.url.includes("update") ||
      config.url.includes("import") ||
      config.url.includes("export")
    ) {
      loadingInstance = Loading.service();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//  定义errorMsg的错误提醒方法
const errorMsg = (message) => {
  return Message({
    message: message,
    type: "error",
    duration: messageDuration,
  });
};

//  很好的响应拦截器
service.interceptors.response.use(
  (response) => {
    if (loadingInstance) {
      loadingInstance.close();
    }
    const { status, data } = response;
    const { code, msg } = data;
    if (code !== successCode && code !== 0) {
      if (code == invalidCode) {
        errorMsg(msg || "后端接口402异常");
        store.dispatch("user/resetToken");
      } else if (code == errorCode) {
        errorMsg(msg || "后端接口500异常");
      } else if (code == noPermissionCode) {
        router.push({
          path: "/401",
        });
      } else {
        errorMsg(msg || "后端接口code异常");
      }
      //  等价于new Promise((resolve, reject) => reject({ code, msg } || "Error"))
      return Promise.reject({ code, msg } || "Error");
    } else {
      return data;
    }
  },
  (error) => {
    if (loadingInstance) {
      loadingInstance.close();
    }
    /*网络连接过程异常处理*/
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    if (message.includes("timeout")) {
      message = "后端接口请求超时";
    }
    if (message.includes("Request failed with status code")) {
      message = "后端接口" + message.substr(message.length - 3) + "异常";
    }
    errorMsg(message || "后端接口未知异常");
    return Promise.reject(error);
  }
);
export default service;

3. 在src下新建api文件夹, 然后建立相关的api集合
import request from "@/utils/request";

export function getList(data) {
  return request({
    url: "/face/list",
    method: "post",
    data,
  });
}

export function doEdit(data) {
  return request({
    url: "/face/edit",
    method: "post",
    data,
  });
}

export function doDelete(data) {
  return request({
    url: "/face/delete",
    method: "post",
    data,
  });
}

然后就可以在页面里快乐的引用了~~

JSON.stringify(data, null, 2)

你可能感兴趣的:(工作经验)