当前位置: 首页 > news >正文

Vue3+TypeScript二次封装axios

安装如下
npm install axios

第一步:创建config配置文件,用于存放请求后端的ip地址,用于后期打包后便于修改ip地址。

注:typescript要求参数要有类型。(ES6 定义对象 属性 类型 修改的是属性的值)

interface Config {getCookieExpires(): number;getBaseIP(): string;getBaseUrl(): string;getSQLServerBaseUrl(): string;
}const config: Config = {getCookieExpires() {return 5;},getBaseIP() {const developmentIP = "";return developmentIP;},getBaseUrl() {const developmentUrl = `http://${this.getBaseIP()}:8580/edu_examandmanage_back`;return developmentUrl;},getSQLServerBaseUrl() {const developmentSQLServerUrl = `http://${this.getBaseIP()}:9191/edu_examandmanage_back`;return developmentSQLServerUrl;},
};export default config;


 

第二步:封装axios于http文件中

注:{ type AxiosInstance, type AxiosResponse }要用type

import axios, { type AxiosInstance, type AxiosResponse } from "axios"
import config from '@/config';const http:AxiosInstance = axios.create({baseURL: config.getBaseUrl(),timeout: 30000, // 请求超时时间headers: {'Content-Type': 'application/json'}
});// 请求拦截器
http.interceptors.request.use((config) => {const token = sessionStorage.getItem('token');if (token) {config.headers.Authorization = `Bearer ${token}`;}return config;},(error) => Promise.reject(error)
);// 响应拦截器
http.interceptors.response.use((response) => response,(error) => {if (error.response?.status === 403) {// 处理权限错误}return Promise.reject(error);}
);export default http;

第三步:调用http实现get、post、delete、put方法

// 公共请求
import http from 'src/lib/http'export const ProcessApi = {// 根据ID获取仪器进度GetInstrumentProgressById(id:number) {return http.get(`/api/progress/getInstrumentProgressById?id=${id}`);},// 根据UserName获取仪器进度getInstrumentProgressByUserNumber(user_number:number) {return http.get(`/api/progress/getInstrumentProgressByUserNumber?user_number=${user_number}`);},
};

第四步:引入在单页面使用(根据组件化开发模式不需要全局注册,只需要在需要的地方引用就可以了)

以下为vue2+JavaScript版本

config.js

//全局配置信息
const config =  {//token在Cookie中存储的天数,默认7天getCookieExpires(){return 5;},getBaseIP(){const developmentIP = "";return developmentIP;},getBaseUrl(){const developmentUrl = "http://" + this.getBaseIP() + ":8580/edu_examandmanage_back";// const developmentUrl = "http://localhost:8580/edu_examandmanage_back";return developmentUrl;},getSQLServerBaseUrl(){const developmentSQLServerUrl = "http://" + this.getBaseIP() + ":9191/edu_examandmanage_back";// const developmentUrl = "http://localhost:9191/edu_examandmanage_back";return developmentSQLServerUrl;},};export default config;

http.js

import axios from 'axios';
import config from '../config';
import Vue from 'vue';// Create an Axios instance
const http = axios.create({timeout: 30000, // Request timeoutbaseURL: config.getBaseUrl(),headers: {'Content-Type': 'application/json;charset=UTF-8',},
});// Add a request interceptor
http.interceptors.request.use((config) => {// Get the token from localStorageconst token = sessionStorage.getItem('token');// If the token exists, add it to the Authorization headerif (token) {config.headers.Authorization = `Bearer ${token}`;}return config;},(error) => {return Promise.reject(error);}
);// Add a response interceptor
http.interceptors.response.use((response) => {return response;},(error) => {// Check if the error response status is 403if (error.response && error.response.status === 403) {// Use Vuesax to display a notificationVue.prototype.$vs.notification({title: '权限错误',text: '请叫管理员开通权限。',color: 'danger', // Set the notification colorposition: 'top-center',duration: 4000, // Duration in milliseconds});}return Promise.reject(error);}
);export default http;

 ExamApi.js

// 公共请求
import http from '@/lib/http';
export const ExamApi = {UserNeedExamByUserNumber(UserNumber){return http.get('/exam/UserNeedExamByUserNumber', { params: { UserNumber } });},SelectAllQustionByPaperIdUpdate(PaperId){return http.get('/exam/SelectAllQustionByPaperIdUpdate', { params: { PaperId } });},insertRecordFromStartExam(data) {return http.post('/exam/insertRecordFromStartExam', JSON.stringify(data));},insertUserAnswerAndSubmitExamToAddScore(data) {return http.post('/exam/insertUserAnswerAndSubmitExamToAddScore', JSON.stringify(data));},SelectAllQustionFromStore(QuestionId){return http.get('/exam/SelectAllQustionFromStore', { params: { QuestionId } });},addQuestions(data) {return http.post('/exam/addQuestions', JSON.stringify(data));},getUserAnswers(id){return http.get('/exam/RecordAllExamInfoById', { params: { id } });},delteRecordByClassName(classname){return http.post('/exam/delteRecordByClassName', classname);},SelectAllExamInfoByUserNumber(ExamUserNumber){return http.get('/exam/SelectAllExamInfoByUserNumber', { params: { ExamUserNumber } });},SelectAllExamInfo(){return http.get('/exam/SelectAllExamInfo');},DeleteQustionByQuestionId(QuestionId){return http.get('/exam/DeleteQustionByQuestionId', { params: { QuestionId } });},//组卷模块GetAllPaperInfo(){return http.get('/exam/GetAllPaperInfo');},DeleteAnPaper(paperId){return http.get('/exam/DeleteAnPaper', { params: { paperId } });},GenerateAnPaperController(data) {return http.post('/exam/GenerateAnPaperController', JSON.stringify(data));},deleteImageFile(ImageName) {return http.delete("/upload/deleteImageFile", {params: {ImageName: ImageName}});}
}

main.js

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • suid提权的环境搭建+反弹shell
  • 基于 ROS 的Terraform托管服务轻松部署Qwen-VL-Chat
  • 新书宣传:《量子安全:信息保护新纪元》
  • JavaScript高级——关于语句分号的问题
  • redis为什么这么快
  • 组织应在其网络安全策略中考虑MLSecOps吗?
  • MM-PhyQA——一个专门处理高中物理选择题的 LLM 聊天机器人
  • 【网络安全】-文件上传漏洞实战-upload-labs(0~16)
  • 如何用GPU算力卡P100玩黑神话悟空?
  • Python 数学建模——独立性检验
  • spring如何整合druid连接池?
  • 大模型LLM部署学习
  • [数据集][目标检测]乱堆物料检测数据集VOC+YOLO格式1143张1类别
  • 网络安全工程师能赚多少钱一个月?
  • 构建常态化安全防线:XDR的态势感知与自动化响应机制
  • [微信小程序] 使用ES6特性Class后出现编译异常
  • 0x05 Python数据分析,Anaconda八斩刀
  • Docker 1.12实践:Docker Service、Stack与分布式应用捆绑包
  • Docker容器管理
  • download使用浅析
  • IE报vuex requires a Promise polyfill in this browser问题解决
  • Java超时控制的实现
  • Js基础知识(一) - 变量
  • JS专题之继承
  • leetcode386. Lexicographical Numbers
  • mac修复ab及siege安装
  • mongodb--安装和初步使用教程
  • PaddlePaddle-GitHub的正确打开姿势
  • Redis的resp协议
  • Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel
  • Twitter赢在开放,三年创造奇迹
  • vue 个人积累(使用工具,组件)
  • vue--为什么data属性必须是一个函数
  • 产品三维模型在线预览
  • 警报:线上事故之CountDownLatch的威力
  • 理清楚Vue的结构
  • 前端每日实战:61# 视频演示如何用纯 CSS 创作一只咖啡壶
  • 设计模式 开闭原则
  • 使用API自动生成工具优化前端工作流
  • 为什么要用IPython/Jupyter?
  • 为物联网而生:高性能时间序列数据库HiTSDB商业化首发!
  • 终端用户监控:真实用户监控还是模拟监控?
  • nb
  • 3月27日云栖精选夜读 | 从 “城市大脑”实践,瞭望未来城市源起 ...
  • ​一、什么是射频识别?二、射频识别系统组成及工作原理三、射频识别系统分类四、RFID与物联网​
  • #HarmonyOS:Web组件的使用
  • #LLM入门|Prompt#1.7_文本拓展_Expanding
  • (Bean工厂的后处理器入门)学习Spring的第七天
  • (delphi11最新学习资料) Object Pascal 学习笔记---第7章第3节(封装和窗体)
  • (el-Date-Picker)操作(不使用 ts):Element-plus 中 DatePicker 组件的使用及输出想要日期格式需求的解决过程
  • (附源码)ssm高校志愿者服务系统 毕业设计 011648
  • (附源码)计算机毕业设计SSM智慧停车系统
  • (附源码)小程序 交通违法举报系统 毕业设计 242045
  • (含笔试题)深度解析数据在内存中的存储
  • (论文阅读40-45)图像描述1