Vue3+Vite+Axios Request 请求封装(TS版本)
http > index.ts 请求封装
/*
* @Date: 2024-03-30 12:37:05
* @LastEditors: zhong
* @LastEditTime: 2024-03-30 14:12:52
* @FilePath: \app-admin\src\http\index.ts
*/
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { ElMessage } from "element-plus";
// axios 请求配置
const config = {
// baseURL:'http://localhost:8080',
baseURL: '/api',
timeout: 1000
}
// 定义返回值类型
export interface Result<T = any> {
code: number;
msg: string;
data: T;
}
class Http {
// axios 实例
private instance: AxiosInstance;
// 构造函数初始化
constructor(config: AxiosRequestConfig) {
this.instance = axios.create(config);
//定义拦截器
this.interceptors();
}
private interceptors() {
// axios 发送请求之前的处理
this.instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
// 在请求头部携带token
// let token = sessionStorage.getItem('token');
let token = '';
if (token) {
config.headers!['token'] = token;
// 把 token 放到 headers 里面
// (config.headers as AxiosRequestHeaders).token = token;
}
console.log(config);
return config;
}, (error: any) => {
error.data = {};
error.data.msg = '服务器异常,请联系管理员!'
return error;
})
// axios 请求返回之后的处理
// 请求返回处理
this.instance.interceptors.response.use((res: AxiosResponse) => {
// console.log(res.data);
if (res.data.code != 200) {
ElMessage.error(res.data.msg || '服务器出错啦');
return Promise.reject(res.data.msg || '服务器出错啦');
} else {
return res.data;
}
}, (error) => {
console.log('进入错误!');
error.data = {};
if (error && error.response) {
switch (error.response.status) {
case 400:
error.data.msg = "错误请求";
ElMessage.error(error.data.msg);
break;
case 401:
error.data.msg = "未授权,请登录";
ElMessage.error(error.data.msg);
break;
case 403:
error.data.msg = "拒绝访问";
ElMessage.error(error.data.msg);
break;
case 404:
error.data.msg = "请求错误,未找到该资源";
ElMessage.error(error.data.msg);
break;
case 405:
error.data.msg = "请求方法未允许";
ElMessage.error(error.data.msg);
break;
case 408:
error.data.msg = "请求超时";
ElMessage.error(error.data.msg);
break;
case 500:
error.data.msg = "服务器端出错";
ElMessage.error(error.data.msg);
break;
case 501:
error.data.msg = "网络未实现";
ElMessage.error(error.data.msg);
break;
case 502:
error.data.msg = "网络错误";
ElMessage.error(error.data.msg);
break;
case 503:
error.data.msg = "服务不可用";
ElMessage.error(error.data.msg);
break;
case 504:
error.data.msg = "网络超时";
ElMessage.error(error.data.msg);
break;
case 505:
error.data.msg = "http版本不支持该请求";
ElMessage.error(error.data.msg);
break;
default:
error.data.msg = `连接错误${error.response.status}`;
ElMessage.error(error.data.msg);
}
} else {
error.data.msg = "连接到服务器失败";
ElMessage.error(error.data.msg)
}
return Promise.reject(error);
})
}
// GET方法
get<T = Result>(url: string, params?: object): Promise<T> {
return this.instance.get(url, { params });
}
// POST方法
post<T = Result>(url: string, data?: object): Promise<T> {
return this.instance.post(url, data);
}
// PUT方法
put<T = Result>(url: string, data?: object): Promise<T> {
return this.instance.put(url, data );
}
// DELETE方法
delete<T = Result>(url: string): Promise<T> {
return this.instance.delete(url);
}
}
export default new Http(config);
vite.config.ts 配置跨域
/*
* @Date: 2024-03-24 15:19:01
* @LastEditors: zhong
* @LastEditTime: 2024-03-30 13:48:06
* @FilePath: \app-admin\vite.config.ts
*/
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],server:{
host: "0.0.0.0", // 解决控制台: NextWork:use --host to expose
port: 8080,
hmr: true, // 开启热更新
open: true, // 启动在浏览器打开
proxy: {
'/api': {
target: 'http://localhost:9999',
// target就是你要访问的目标地址,可以是基础地址,这样方便在这个网站的其他api口调用数据
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
// 要记得加rewrite这句
},
},
},
resolve: {
alias: [
{
find: '@',
replacement: resolve(__dirname, 'src')
}
]
}
})
user > UserModel.ts 用户数据模型
/*
* @Date: 2024-03-30 13:16:03
* @LastEditors: zhong
* @LastEditTime: 2024-03-30 13:19:17
* @FilePath: \app-admin\src\api\user\userModel.ts
*/
// 定义用户的数据类型
export type User = {
userId?: string,
username: string,
password: string,
nickName: string,
phone: string,
sex: string,
status: string,
}
user > index.ts 请求函数
/*
* @Date: 2024-03-30 13:15:25
* @LastEditors: zhong
* @LastEditTime: 2024-03-30 13:58:40
* @FilePath: \app-admin\src\api\user\index.ts
*/
import http from "@/http";
import { User } from "./userModel";
// 新增
export const addAdminUserApi = (parm: User) => {
console.log(parm);
return http.post("/api/sysUser", parm)
}
AdminUser.vue 使用请求函数
<!--
* @Date: 2024-03-24 18:14:27
* @LastEditors: zhong
* @LastEditTime: 2024-03-30 14:03:00
* @FilePath: \app-admin\src\views\system\AdminUser.vue
-->
<template>
<el-main>
<!-- 搜索栏 -->
<el-form :model="searchParm" ref="form" :inline="true" size="default">
<el-form-item>
<el-input v-model="searchParm.nickName" placeholder="请输入姓名"></el-input>
</el-form-item>
<el-form-item>
<el-button icon="search">搜索</el-button>
<el-button icon="closeBold" type="danger">重置</el-button>
<el-button icon="plus" type="primary" @click="addBtn">新增</el-button>
</el-form-item>
</el-form>
<!-- 新增 -->
<SystemDialog :title="dialog.title" :height="dialog.height" :width="dialog.width" :visible="dialog.visible"
@on-close="onClose" @on-confirm="commit">
<template v-slot:content>
<!-- 新增内容表单 -->
<el-form :model="addAdminParm" ref="addRef" :rules="rules" label-width="80px" :inline="false"
size="default">
<el-form-item prop="nickName" label="姓名:">
<el-input v-model="addAdminParm.nickName"></el-input>
</el-form-item>
<el-form-item prop="sex" label="性别:">
<el-radio-group v-model="addAdminParm.sex">
<el-radio value="1" size="large" border>男</el-radio>
<el-radio value="2" size="large" border>女</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item prop="phone" label="电话:">
<el-input v-model="addAdminParm.phone"></el-input>
</el-form-item>
<el-form-item prop="username" label="账号:">
<el-input v-model="addAdminParm.username"></el-input>
</el-form-item>
<el-form-item prop="password" label="密码:">
<el-input v-model="addAdminParm.password"></el-input>
</el-form-item>
<el-form-item prop="status" label="状态:">
<el-radio-group v-model="addAdminParm.status">
<el-radio value="1" size="large" border>启用</el-radio>
<el-radio value="2" size="large" border>停用</el-radio>
</el-radio-group>
</el-form-item>
</el-form>
</template>
</SystemDialog>
</el-main>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import SystemDialog from '@/components/SystemDialog/SystemDialog.vue';
import useDialog from '@/hooks/useDialog';
import { ElMessage, FormInstance } from 'element-plus';
import { addAdminUserApi } from '@/api/user'
// 获取弹框属性
const { dialog, onClose } = useDialog();
// 搜索绑定对对象
const searchParm = reactive({
nickName: ""
})
// 表单 ref 属性
const addRef = ref<FormInstance>()
// 新增按钮
const addBtn = () => {
dialog.height = 320;
dialog.visible = true;
}
// 新增表单内容
const addAdminParm = reactive({
userId: "",
username: "",
password: "",
nickName: "",
phone: "",
sex: "",
status: ""
})
// 表单验证规则
const rules = {
nickName: [
{ required: true, message: '请填写您的昵称', trigger: 'blur' },
{ min: 0, max: 12, message: 'Length should be 0 to 12', trigger: 'blur' },
],
sex: [{ required: true, message: '请选择您的性别', trigger: 'blur' }],
phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
userPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }],
status: [{ required: true, message: '请选择账号状态', trigger: 'blur' }],
}
// 提交表单
const commit = () => {
addRef.value?.validate(async (valid) => {
if (valid) {
// 提交数据
const res = await addAdminUserApi(addAdminParm);
if (res && res.code == 200) {
// 信息提示
ElMessage.success(res.msg);
// 提交成功 关闭弹框
dialog.visible = false;
}
}
});
}
</script>
<style lang="scss" scoped></style>
标签:Axios,string,Request,TS,break,error,msg,ElMessage,data
From: https://blog.csdn.net/weixin_56050344/article/details/137172550