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

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 timeout
  baseURL: config.getBaseUrl(),
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});

// Add a request interceptor
http.interceptors.request.use(
    (config) => {
      // Get the token from localStorage
      const token = sessionStorage.getItem('token');

      // If the token exists, add it to the Authorization header
      if (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 403
        if (error.response && error.response.status === 403) {
            // Use Vuesax to display a notification
            Vue.prototype.$vs.notification({
                title: '权限错误',
                text: '请叫管理员开通权限。',
                color: 'danger', // Set the notification color
                position: '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


http://www.kler.cn/a/305499.html

相关文章:

  • 封装el-menu
  • MYSQL 库,表 基本操作
  • 网络远程操控
  • 实验一:自建Docker注册中心
  • 【Vue】Vue3.0(二十一)Vue 3.0中 的$event使用示例
  • SpringSecurity源码中核心类
  • C++多态讲解
  • 进阶岛 任务3: LMDeploy 量化部署进阶实践
  • 在云服务器上安装配置 MySQL 并开启远程访问(详细教程)
  • JVM锁的优化与逃逸分析
  • CVE-2024-21096:MySQLDump提权漏洞分析
  • 基于深度学习的生物网络推理
  • 论文解读:利用大模型进行基于上下文的OCR校正
  • linux系统安装miniconda3
  • 云手机哪一款好用?手游专用云手机一览!VMOS云手机
  • Java学习Day41:骑龙救!(springMVC)
  • 在单片机中,处于高阻态是什么状态
  • GEE 教程:利用Google Dynamic数据进行逐月指定区域的土地分类数据提取分析
  • 【mysql】mysql之读写分离以及分库分表
  • Remote Connection Software,远程连接软件
  • 【Web】XGCTF 西瓜杯 超详细题解
  • 代码随想录:单调栈1-3
  • 浅谈人工智能之基于本地大模型的前后端平台开发示例
  • LINQ 和 LINQ扩展方法 (1)
  • OkHttp Interceptor日志上报
  • 「OC」事件点击demo合集