Axios请求封装

This commit is contained in:
Amadeus 2024-05-05 17:11:26 +08:00
parent bbcceff052
commit 259a72fbc5
5 changed files with 197 additions and 10 deletions

View File

@ -9,6 +9,7 @@
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"@element-plus/icons-vue": "^2.3.1", "@element-plus/icons-vue": "^2.3.1",
"axios": "^1.6.8",
"element-plus": "^2.7.2", "element-plus": "^2.7.2",
"vue": "^3.3.4", "vue": "^3.3.4",
"vue-router": "^4.3.2" "vue-router": "^4.3.2"
@ -725,6 +726,21 @@
"resolved": "https://registry.npmmirror.com/async-validator/-/async-validator-4.2.5.tgz", "resolved": "https://registry.npmmirror.com/async-validator/-/async-validator-4.2.5.tgz",
"integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==" "integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg=="
}, },
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmmirror.com/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmmirror.com/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/balanced-match": { "node_modules/balanced-match": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz",
@ -782,6 +798,17 @@
"fsevents": "~2.3.2" "fsevents": "~2.3.2"
} }
}, },
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/confbox": { "node_modules/confbox": {
"version": "0.1.7", "version": "0.1.7",
"resolved": "https://registry.npmmirror.com/confbox/-/confbox-0.1.7.tgz", "resolved": "https://registry.npmmirror.com/confbox/-/confbox-0.1.7.tgz",
@ -815,6 +842,14 @@
} }
} }
}, },
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/element-plus": { "node_modules/element-plus": {
"version": "2.7.2", "version": "2.7.2",
"resolved": "https://registry.npmmirror.com/element-plus/-/element-plus-2.7.2.tgz", "resolved": "https://registry.npmmirror.com/element-plus/-/element-plus-2.7.2.tgz",
@ -941,6 +976,32 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/follow-redirects": {
"version": "1.15.6",
"resolved": "https://registry.npmmirror.com/follow-redirects/-/follow-redirects-1.15.6.tgz",
"integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==",
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmmirror.com/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/fsevents": { "node_modules/fsevents": {
"version": "2.3.3", "version": "2.3.3",
"resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz", "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz",
@ -1104,6 +1165,25 @@
"node": ">=8.6" "node": ">=8.6"
} }
}, },
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/minimatch": { "node_modules/minimatch": {
"version": "9.0.4", "version": "9.0.4",
"resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-9.0.4.tgz", "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-9.0.4.tgz",
@ -1209,6 +1289,11 @@
"node": "^10 || ^12 || >=14" "node": "^10 || ^12 || >=14"
} }
}, },
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
},
"node_modules/queue-microtask": { "node_modules/queue-microtask": {
"version": "1.2.3", "version": "1.2.3",
"resolved": "https://registry.npmmirror.com/queue-microtask/-/queue-microtask-1.2.3.tgz", "resolved": "https://registry.npmmirror.com/queue-microtask/-/queue-microtask-1.2.3.tgz",

View File

@ -9,6 +9,7 @@
}, },
"dependencies": { "dependencies": {
"@element-plus/icons-vue": "^2.3.1", "@element-plus/icons-vue": "^2.3.1",
"axios": "^1.6.8",
"element-plus": "^2.7.2", "element-plus": "^2.7.2",
"vue": "^3.3.4", "vue": "^3.3.4",
"vue-router": "^4.3.2" "vue-router": "^4.3.2"

View File

@ -3,6 +3,9 @@
import { createApp } from 'vue' import { createApp } from 'vue'
import App from './App.vue' import App from './App.vue'
import router from "@/router"; import router from "@/router";
import axios from "axios";
axios.defaults.baseURL = 'http://localhost:8080'
const app = createApp(App) const app = createApp(App)
app.use(router) app.use(router)

View File

@ -0,0 +1,75 @@
import axios from 'axios'
import {ElMessage} from "element-plus";
const authItemName = "access_token"
const defaultFailure = (message , code , url) => {
console.warn(`请求地址: ${url} , 状态码: ${code} , 错误信息: ${message}`)
ElMessage.warning(message)
}
const defaultError = (err) => {
console.error(err)
ElMessage.warning('发生了一些错误,请联系管理员')
}
function takeAccess() {
const str = localStorage.getItem(authItemName) || sessionStorage.getItem(authItemName)
if (!str) return null;
const authObj = JSON.parse(str)
if (authObj.expire <= new Date()){
deleteAccessToken()
ElMessage.warning('登录状态已过期,请重新登录')
return null
}
return authObj.token
}
function storeAccessToken(token , remember , expire) {
const authObj = {token: token ,expire: expire}
const str =JSON.stringify(authObj)
if (remember)
localStorage.setItem(authItemName , str)
else
sessionStorage.setItem(authItemName , str)
}
function deleteAccessToken(){
localStorage.removeItem(authItemName)
sessionStorage.removeItem(authItemName)
}
function internalPost(url , data , header , success ,failure , error = defaultError) {
axios.post(url,data, {headers: header}).then(({data}) => {
if (data.code ===200){
success(data.data)
}else {
failure(data.message , data.code , url)
}
}).catch(err => error(err))
}
function internalGet(url , header , success ,failure , error = defaultError) {
axios.get(url,{headers: header}).then(({data}) => {
if (data.code ===200){
success(data.data)
}else {
failure(data.message , data.code , url)
}
}) .catch(err => error(err))
}
function login(username , password , remember , success , failure = defaultFailure) {
internalPost('api/auth/login', {
username: username ,
password: password
}, {
'Content-Type': 'application/x-www-form-urlencoded'
},(data)=> {
storeAccessToken(remember, data.token , data.expire)
ElMessage.success(`登录成功,欢迎 ${data.username} 来到我们的系统`)
success(data)
}, failure)
}
export {login}

View File

@ -1,12 +1,35 @@
<script setup> <script setup>
import { User , Lock} from '@element-plus/icons-vue' import { User , Lock} from '@element-plus/icons-vue'
import {reactive} from "vue"; import {reactive, ref} from "vue";
import {login} from "@/net";
const from = reactive({ const formRef = ref()
const form = reactive({
username: '', username: '',
password: '', password: '',
remember: false remember: false
}) })
const rule = {
username: [
{required: true ,message: '请输入用户名'}
],
password: [
{required: true ,message: '请输入密码'}
]
}
function userLogin(){
formRef.value.validate((valid) => {
if (valid){
login(form.username , form.password ,form.remember , ()=>{
})
}
})
}
</script> </script>
<template> <template>
@ -16,16 +39,16 @@ const from = reactive({
<div style="font-size: 14px;color: gray">在进入系统之前,请先输入用户名和密码进行登录</div> <div style="font-size: 14px;color: gray">在进入系统之前,请先输入用户名和密码进行登录</div>
</div> </div>
<div style="margin-top: 50px"> <div style="margin-top: 50px">
<el-form v-model="from"> <el-form :model="form" :rules="rule" ref="formRef">
<el-form-item> <el-form-item prop="username">
<el-input v-model="from.username" maxlength="10" type="text" placeholder="用户名/邮箱"> <el-input v-model="form.username" maxlength="10" type="text" placeholder="用户名/邮箱">
<template #prefix> <template #prefix>
<el-icon><User/></el-icon> <el-icon><User/></el-icon>
</template> </template>
</el-input> </el-input>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item prop="password">
<el-input v-model="from.password" maxlength="20" placeholder="密码"> <el-input v-model="form.password" type="password" maxlength="20" placeholder="密码">
<template #prefix> <template #prefix>
<el-icon><Lock /></el-icon> <el-icon><Lock /></el-icon>
</template> </template>
@ -33,8 +56,8 @@ const from = reactive({
</el-form-item> </el-form-item>
<el-row> <el-row>
<el-col :span="12" style="text-align: left"> <el-col :span="12" style="text-align: left">
<el-form-item> <el-form-item prop="remember">
<el-checkbox v-model="from.remember" label="记住我"/> <el-checkbox v-model="form.remember" label="记住我"/>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col :span="12" style="text-align: right"> <el-col :span="12" style="text-align: right">
@ -44,7 +67,7 @@ const from = reactive({
</el-form> </el-form>
</div> </div>
<div style="margin-top: 40px"> <div style="margin-top: 40px">
<el-button style="width: 270px" type="success" plain>立即登录</el-button> <el-button @click="userLogin" style="width: 270px" type="success" plain>立即登录</el-button>
</div> </div>
<el-divider> <el-divider>
<span style="font-size: 13px ; color: gray">没有账户?</span> <span style="font-size: 13px ; color: gray">没有账户?</span>