网站基础开发成本,影楼公共网站,厦门网站建设多少钱,wordpress中国vue项目#xff0c;封装axios请求方式和响应状态码#xff1b;以及接口的api封装#xff1b;
目录结构#xff1a; 1.具体在src/utils/request.js下封装axios#xff1a; ①引入axios和router ②引入element-ui是为了用提示组件 和加载组件#xff08;可选择去掉#…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 {// 成功status200 对响应数据做点什么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})
}
// 获取学科网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获取使用
templatediv接口返回参数div{{ data }}/div!-- el-input v-modelinput placeholder请输入内容 / --button clickgetlistRequestget 获取列表/buttonbutton clickgetClassRequestget动态参数 获取班级/buttonbutton clickbtnRequestpost点击获取url/buttonbutton clickgetKnowledgeRequestpost传参获取知识点/buttonbutton clickdownloadExcelRequestget文件流下载 配置config/button/div
/templatescript
// 引入接口方法
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;charsetutf-8const 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 学情报告.xlsxa.click()window.URL.revokeObjectURL(blob)a.remove()})}}
}
/scriptstyle
/style
4.页面和接口展示 成功200 需要配置config的下载
请求失败提示