100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > vue项目请求封装;axios封装使用

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

时间:2022-04-10 03:11:34

相关推荐

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 然后调用上面封装的axiosconfig = 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}`)}// 获取学科网urlexport 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 = 1932115674972160getClass(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 = 1943647285534911downloadExcel(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 = urldocument.body.appendChild(a)a.download = '学情报告.xlsx'a.click()window.URL.revokeObjectURL(blob)a.remove()})}}}</script><style></style>

4.页面和接口展示:

成功200:

需要配置config的下载:

请求失败提示:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。