如何return返回 axios 的返回值


在前端页面中使用 axios 时,需要获得返回值,进行后续的操作。

问题描述

如下,返回 isBol 的值,这样写只能返回 空

<div id="app">
  <input type="button" value="get请求" id="get" />
  <input type="button" value="post请求" id="post" />
  <input type="button" value="post请求2" id="post2" />
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  function login() {
    let isBol = ""
    axios.post("http://localhost:8080//final01_war_exploded/users/actions/login", {username:"100001", password:"123456"})
      .then(function(response) {
          console.log(response)
          isBol = true
      }, function(err){
          console.log(err)
          isBol  = false
      })

    return isBol
  }
  
  /*
  post请求
  */
  document.querySelector("#post2").onclick = function(){
      if(login()) {
        console.log("shaqk")
        location = "vue计数器.html"
      }
  }
</script>

分析原因

axios请求是异步的 ,需要使用async/await

解决方法

在函数名前添加 async 且在 axios 前添加 await

<script>
async function login() {
  let isBol = ""
  await axios.post("http://localhost:8080//final01_war_exploded/users/actions/login", {username:"100001", password:"123456"})
    .then(function(response) {
        console.log(response)
        isBol = true
    }, function(err){
        console.log(err)
        isBol  = false
    })

  return isBol
}
</script>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM