安装axios,在net文件下新建index.js,封装InternalPsot请求:
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))
}
由于之前后端统一封装了返回数据,可以通过 code来判断状态
编写默认的failure和error方法:
const defaultFailure=(message,code,url)=>{
console.warn(`请求地址:${url},状态码:${code},错误信息:${message}`)
ElMessage.warning(message)
}
const defaultError=(err)=>{
console.error(err)
ElMessage.warning('发生了一些错误,请联系管理员')
}
封装InternalGet请求:
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))
}
封装login请求:
function login(username,password,remember,success,failure=defaultFailure()){
internalPost('/api/auth/login',{
username:username,
password:password
},{
'Content-Type':'application/x-www-form-urlencoded'
},(data)=>{
ElMessage.success(`登陆成功,欢迎${data.username}来到我们的系统`)
success(data)
},failure)
}
由于后端使用了jwt,登录后服务器会发送token,我们需要将token保存,退出登陆时需要将token删除,编写保存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)
}
}
如果用户勾选remember,存入localstorage,不勾选存入sessionstorage
后续访问页面时需要获取token,编写takeaccesstoken函数:
function takeAccessToken(){
const Storage=localStorage.getItem(authItemName)||sessionStorage.getItem(authItemName)
if (!Storage)return null
const authObj=JSON.parse(str)
if(authObj.expire<=new Date()){
deleteAccessToken()
ElMessage.warning('登录状态已过期,请重新登录')
return null
}
return authObj.token
}
删除token:
function deleteAccessToken(){
localStorage.removeItem(authItemName)
sessionStorage.removeItem(authItemName)
}
在login的返回数据处理中加入:
storeAccessToken(data.token,data.remember.data.expire)
暴露组件:export {login}
在登陆页面绑定:
立即登录
function userLogin(){
formRef.value.validate((valid)=>{
if (valid){
login(form.username,form.password,form.remember).then(res=>{
})
}
})
}
增加输入框规则
const formRef=ref()
const rule={
username: [
{required:true,message:'请输入用户名'}
],
password:[
{required:true,message:'请输入密码'}
]
}
const form =reactive({
username:'',
password:'',
remember:false
});
添加后端基础url:
axios.defaults.baseURL="http://localhost:8080"
Access to XMLHttpRequest at ‘http://localhost:8080/api/auth/login’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
控制台报错跨域请求错误,在下一节中解决