vue项目请求封装;axios封装使用

vue项目,封装axios请求方式和响应状态码;以及接口的api封装;

目录结构:
在这里插入图片描述
1.具体在src/utils/request.js下封装axios:
①引入axios和router
②引入element-ui是为了用提示组件 和加载组件(可选择去掉)
③根据请求拦截器的config配置请求头
④根据响应拦截器的不同状态码做不同处理(状态码需要自己根据项目修改)
简单的request.js封装点击这里,没有封装状态码和提示–可自己配

import axios from "axios";
import router from "./../router";
import { Message, Loading, MessageBox } from "element-ui";

// 设置axios全局默认的BASE-URL, 只要设置了全局的默认base_url,以后的请求会自动拼接上base_url
// -------------------------------注意改成自己的公共url------------------------------------
axios.defaults.baseURL = "http://192.168.1.194/gateway";
axios.defaults.timeout = 10000;

let loading;

// 配置axios的请求拦截器-(每次在请求头上携带后台分配的token-后台判断token是否有效等问题)
axios.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    // console.log('请求到了哟', config.headers.Authorization)

    // 如果有其他的特殊配置 只需要判断config参数 设置即可
    let showLoading = true;
    if (config.loading === false) {
      showLoading = false;
    }

    if (showLoading) {
      loading = Loading.service({
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.08)"
      });
    }

    // 标识系统为AJAX请求
    config.headers["X-Requested-With"] = "XMLHttpRequest";

    // 统一的给config设置 token-------------------------------注意获取方法------------------------------------
    //   config.headers.Authorization = JSON.parse(localStorage.getItem('token'))
    config.headers["Token"] = "97aa8f6b569648c78005240033aa0438";
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器 与后端定义状态是100时候是错误 跳转到登录界面
axios.interceptors.response.use(
  response => {
    // 成功status:200 对响应数据做点什么
    console.log("接口success", response);
    loading && loading.close();

    // 根据接口返回状态码 定义
    const { code, data, message } = response.data;
    if (code) {
      switch (code) {
        case 200:
          return { code, data };
        case 3012:
          return { code, data };
        case 404:
          Message({
            message: "网络请求不存在",
            type: "error",
            duration: 2 * 1000
          });
          return Promise.reject({ code, data });
        case 100:
          localStorage.removeItem("token");
          router.push({
            path: "/login",
            querry: {} // 登录过期 回到登录页
          });
          return Promise.reject({ code, data });
        case 4011:
          Message.closeAll();
          MessageBox.alert("登录超时或身份失效,请重新登录!", "警告", {
            customClass: "alertbox",
            confirmButtonText: "确定",
            type: "warning",
            center: true,
            callback: action => {
              // location.reload()
              router.push("/");
            }
          });
          return Promise.reject({ code, data });
        case 4002:
        default:
          Message({
            message: message || "Error",
            type: "error",
            duration: 5 * 1000
          });
          return Promise.reject({ code, data });
      }
    }
    //   return response.data
  },
  error => {
    loading && loading.close();
    console.log("接口error", error, error.response);

    const { status } = error.response;
    switch (status) {
      case 500:
        Message.closeAll();
        Message({
          message: "请求超时",
          type: "error",
          duration: 3 * 1000
        });
        break;
      case 700:
        Message.closeAll();
        Message({
          message: "网络中断",
          type: "error",
          duration: 3 * 1000
        });
        break;
      default:
        Message({
          message: error.message,
          type: "error",
          duration: 3 * 1000
        });
    }
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

const $http = {};

$http.get = function(url, data, config) {
  //  这一步把api方法里的  地址 参数 配置传入进来 配置到config 然后调用上面封装的axios
  config = config || {};
  config.url = url;
  config.method = "get";
  config.params = data;
  return axios.request(config);
};

$http.delete = function(url, data, config) {
  config = config || {};
  config.url = url;
  config.method = "delete";
  config.params = data;
  return axios.request(config);
};

$http.post = function(url, data, config) {
  config = config || {};
  config.url = url;
  config.method = "post";
  config.data = data;
  return axios.request(config);
};

$http.put = function(url, data, config) {
  config = config || {};
  config.url = url;
  config.method = "put";
  config.data = data;
  return axios.request(config);
};

export { axios, $http };

2.接口方法封装 src/api/way.js:
①引入封装的$http

②使用$http.get(url,data,config) ; 下方的函数方法都是可以接受三个参数的 分别是 地址 参数 配置 三个参数可以由组件内使用的函数function传入

③在组件内使用,接受传递的参数和配置(详见test.vue组件内的方法)

以下get post put delete 请求均有;且对于不同的请求需要配置的config也有

import { $http } from '@/utils/request'

// $http.get(url,data,config)
// 下方的函数方法都是可以接受三个参数的 分别是 地址 参数 配置   三个参数可以由函数function传入

// 获取详情
export function getlist() {
  return $http.get(`main/queTactic/list`)
}
// 获取班级列表
export function getClass(teacherId) {
  return $http.get(`/basis/teacher/queryTeacherClass/${teacherId}`)
}
// 获取学科网url
export function getUrl() {
  return $http.post(`/auth/api/authorize`)
}
// 获取知识点
export function getKnowledgeIdByChapterIds(data) {
  return $http.post(`/question/message/getKnowledgeIdByChapterIds`, data)
}
// 修改出题策略
export function editTactics(data) {
  return $http.put('main/queTactic', data)
}
// 个性化组题删除题
export function indiviDelete(data) {
  return $http.delete(`/main/personal/deleteQuestionPersonalJob`, data)
}
// 特殊的传参---------例如  文件流下载 需要设置配置responseType  否则下载的文件打开不了-----------
export function downloadExcel(examId) {
  return $http.get(`main/statistics/report/${examId}/export/questionExcel`, null, { responseType: 'blob' })
// 下方请求也可以 但是需要最上方import引入之前封装的axios
//   return axios.request({
//     url: `main/statistics/report/${examId}/export/questionExcel`,
//     responseType: 'blob',
//     method: 'get'
//   })
}

3.scr/views/test.vue在组件内使用接口方法:
①引入way.js内的接口方法:
②传递参数
③通过.then()获取使用

<template>
  <div>
    接口返回参数
    <div>{{ data }}</div>
    <!-- <el-input v-model="input" placeholder="请输入内容" /> -->
    <button @click="getlistRequest">get 获取列表</button>
    <button @click="getClassRequest">get动态参数 获取班级</button>
    <button @click="btnRequest">post点击获取url</button>
    <button @click="getKnowledgeRequest">post传参获取知识点</button>
    <button @click="downloadExcelRequest">get文件流下载  配置config</button>
  </div>
</template>

<script>
//  引入接口方法
import { getlist, getUrl, getClass, getKnowledgeIdByChapterIds, downloadExcel } from '@/api/way.js'
export default {
  data() {
    return {
      input: '',
      data: null
    }
  },
  methods: {
    getlistRequest() {
      getlist().then(res => {
        console.log(res.data)
        this.data = res.data
      })
    },
    getClassRequest() {
      const data = 1932115674972160
      getClass(data).then(res => {
        console.log(res.data)
        this.data = res.data
      })
    },
    btnRequest() {
      getUrl().then(res => { this.data = res.data })
    },
    getKnowledgeRequest() {
      const data = {
        chapterIds: [22394],
        schoolId: 39
      }
      getKnowledgeIdByChapterIds(data).then(res => {
        console.log(res.data)
        this.data = res.data
      })
    },
    downloadExcelRequest() {
      const data = 1943647285534911
      downloadExcel(data).then(res => {
        const type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
        const blob = new Blob([res])
        const url = window.URL.createObjectURL(blob, { type: type })
        const a = document.createElement('a')
        a.href = url
        document.body.appendChild(a)
        a.download = '学情报告.xlsx'
        a.click()
        window.URL.revokeObjectURL(blob)
        a.remove()
      })
    }
  }
}
</script>

<style>
</style>

4.页面和接口展示:
成功200:
在这里插入图片描述
需要配置config的下载:
在这里插入图片描述

请求失败提示:在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值