• Axios请求封装


    安装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))
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    由于之前后端统一封装了返回数据,可以通过 code来判断状态

    编写默认的failure和error方法:

    const defaultFailure=(message,code,url)=>{
        console.warn(`请求地址:${url},状态码:${code},错误信息:${message}`)
        ElMessage.warning(message)
    }
    
    const defaultError=(err)=>{
        console.error(err)
        ElMessage.warning('发生了一些错误,请联系管理员')
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    封装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))
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    封装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)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    由于后端使用了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)
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    如果用户勾选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
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    删除token:

    function  deleteAccessToken(){
        localStorage.removeItem(authItemName)
        sessionStorage.removeItem(authItemName)
    }
    
    • 1
    • 2
    • 3
    • 4

    在login的返回数据处理中加入:

    storeAccessToken(data.token,data.remember.data.expire)
    
    • 1

    暴露组件:export {login}

    在登陆页面绑定:

     立即登录
    
    • 1
    function userLogin(){
      formRef.value.validate((valid)=>{
        if (valid){
          login(form.username,form.password,form.remember).then(res=>{
    
          })
        }
      })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    增加输入框规则

    
    
    const formRef=ref()
    const rule={
      username: [
        {required:true,message:'请输入用户名'}
      ],
      password:[
        {required:true,message:'请输入密码'}
      ]
    }
    
    const form =reactive({
      username:'',
      password:'',
      remember:false
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    添加后端基础url:

    axios.defaults.baseURL="http://localhost:8080"
    
    • 1

    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.

    控制台报错跨域请求错误,在下一节中解决

  • 相关阅读:
    spring cloud gateWay集成knife4j实现文档聚合
    【SpringBoot】8.SpringBoot中的异步任务
    mysql 之进阶查询语句
    protobuf协议详解
    图片转文字怎么转?这些方法我只告诉你
    网络信息通信的安全问题以及解决方法
    node-xlsx - 简单几行代码处理导入、导出 excel 表格数据,免费开源的 javascript 工具库
    一文了解NFT的六大交易平台
    手写数字识别--神经网络实验
    [linux] 由创建用户开始
  • 原文地址:https://blog.csdn.net/qq_40369277/article/details/133309839