如何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