登录请求的实现
安装axios
封装Request
完整代码:
import axios from 'axios'
import { ElLoading } from 'element-plus';
import message from '@/utils/Message';
import router from '@/router'
const contentTypeForm = "application/x-www-form-urlencoded;chaset-UTF-8";
const contentTypeJson = "application/json";
const contentTypeFile = "application/form-data";
const request = (config) => {
const {url,params} = config;
let dataType = config.dataType;
let showLoading = config.showLoading;
dataType = dataType?"form":dataType;
showLoading = showLoading ? true:showLoading;
let contentType = contentTypeForm;
if(dataType === "json"){
contentType = contentTypeJson
}else if(dataType === "file"){
contentType = contentTypeFile
let param = new FormData();
for(let key in params){
param.append(key,params[key]);
}
params = param;
}
const instantce = axios.create({
baseURL:"/api",
timeout:10*1000,
headers:{
'Content-Type':contentType,
'X-Requested-With':'XMLHttpRequest',
}
})
let loading = null;
instantce.interceptors.request.use(
(config)=>{
if(showLoading){
loading = ElLoading.service({
lock:true,
text:'加载中......',
background:'rgba(0,0,0,0.7)',
})
}
return config;
},
(error)=>{
if(showLoading&&loading){
loading.close();
}
message.error(error);
return Promise.reject("发送请求失败");
}
)
//请求后拦截
instantce.interceptors.response.use(
(response)=>{
if(showLoading&&loading){
loading.close();
}
const responseData = response.data;
// debugger;
if(responseData.status == "error"){
if(config.errorCallback){
config.errorCallback();
}
return Promise.reject(responseData.info);
}else{
if(responseData.code==200){
return responseData;
}else if(responseData.code==902){
setTimeout(()=>{
router.push("/login")
},2000)
return Promise.reject("登陆超时");
}
}
},
(error)=>{
if(showLoading&&loading){
loading.close();
}
return Promise.reject("网络异常");
}
)
return instantce.post(url,params).catch(error=>{
message.error(error);
return null;
})
}
export default request;
前端登录函数
封装的Message
import { ElMessage } from 'element-plus';
const message = {
error:(msg)=>{
ElMessage({
message:msg,
type:'error',
duration:2000
})
},
success:(msg)=>{
ElMessage({
message:msg,
type:'success',
duration:2000
})
},
warning:(msg)=>{
ElMessage({
message:msg,
type:'warning',
duration:2000
})
},
}
export default message;
登陆代码
<template>
<div class="login-body">
<div class="login-panel">
<div class="login-title">用户登录</div>
<el-form :model="formData" :rules="rules" ref="formDataRef">
<el-form-item prop="account">
<el-input
placeholder="请输入账号"
v-model="formData.account"
size="large"
>
<template #prefix>
<span class="iconfont icon-account"></span>
</template>
</el-input>
</el-form-item>
<el-form-item prop="password">
<el-input
placeholder="请输入密码"
v-model="formData.password"
size="large"
type="password"
>
<template #prefix>
<span class="iconfont icon-password"></span>
</template>
</el-input>
</el-form-item>
<el-form-item prop="checkCode">
<div class="check-code-panel">
<el-input
placeholder="请输入验证码"
v-model="formData.checkCode"
class="input-panel"
size="large"
@keyup.enter.native="login"
/>
<img
:src="checkCodeUrl"
class="check-code"
@click="changeCheckCode"
/>
</div>
</el-form-item>
<el-form-item label="">
<el-checkbox v-model="formData.rememberMe" :label="true"
>记住我
</el-checkbox>
</el-form-item>
<el-form-item label="">
<el-button type="primary" :style="{ width: '100%' }" @click="login">
登录
</el-button>
</el-form-item>
</el-form>
</div>
</div>
</template>
<script setup>
import VueCookies from "vue-cookies";
import md5 from "js-md5";
import { getCurrentInstance, reactive, ref } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
const { proxy } = getCurrentInstance();
const api = {
checkCode: "api/checkCode",
login: "/login",
};
const checkCodeUrl = ref(api.checkCode);
const changeCheckCode = () => {
checkCodeUrl.value = api.checkCode + "?" + new Date().getTime();
};
//表单相关
const formDataRef = ref();
const formData = reactive({});
const rules = {
account: [
{
required: true,
message: "请输入用户名",
},
],
password: [
{
required: true,
message: "请输入密码",
},
],
checkCode: [
{
required: true,
message: "请输入验证码",
},
],
};
const init = () => {
const loginInfo = VueCookies.get("loginInfo");
if (!loginInfo) {
return;
}
Object.assign(formData, loginInfo);
};
init();
const login = () => {
formDataRef.value.validate(async (valid) => {
if (!valid) {
return;
}
let cookieloginInfo = VueCookies.get("loginInfo");
let cookiesPassword =
cookieloginInfo == null ? null : cookieloginInfo.password;
if (formData.password !== cookiesPassword) {
formData.password = md5(formData.password);
}
let params = {
account: formData.account,
password: formData.password,
checkCode: formData.checkCode,
};
let result = await proxy.Request({
url: api.login,
params: params,
errorCallback: () => {
changeCheckCode();
},
});
if (!result) {
return;
}
proxy.Message.success("登陆成功");
setTimeout(() => {
router.push("/");
}, 1500);
const loginInfo = {
account: params.account,
password: params.password,
rememberMe: formData.rememberMe,
};
VueCookies.set("userInfo", result.data, 0);
if (formData.rememberMe == 1) {
VueCookies.set("loginInfo", loginInfo, "7d");
}
});
};
</script>
<style lang="scss">
.login-body {
width: "100%";
height: calc(100vh);
background-image: url(../assets/login-bg.jpg);
background-size: cover;
background-position: center;
.login-panel {
float: right;
margin-right: 100px;
margin-top: 100px;
padding: 20px; //内容不顶着边
width: 350px;
border-radius: 5px; //圆角
box-shadow: 2px 2px 10px #ddd; //阴影
background: rgba(255, 255, 255, 0.7);
.login-title {
font-size: 20px;
text-align: center;
margin-bottom: 10px;
}
.check-code-panel {
width: 100%;
display: flex;
align-items: center;
.input-panel {
flex: 1;
// margin-right: 5px;
}
.check-code {
// height: 30px;
margin-right: auto;
margin-left: 5px;
cursor: pointer;
}
}
}
}
</style>