首页 > 解决方案 > 如何避免 Vue.JS/Axion 返回 undefined 而响应代码为 200?

问题描述

我有一个非常简单的 Vue.JS / Axion Get 请求来从 API 获取数据。当我调试响应时,它返回 200 状态代码和预期的数组/对象。

但是 Vue.JS 本身返回[Vue warn]: Error in mounted hook: "ReferenceError: response is not defined" 了为什么我不能使用数据。

这是为什么?

我的Javascript代码:

  new Vue({
    el: '#app_name',
    data() {
      return {
        info: null
      };
    },
    mounted() {
      axios
        .get("https://cors-anywhere.herokuapp.com/https://www.api-football.com/demo/api/v2/leagueTable/" + league_id)
        .then((response)=> {
                   this.info = response;
                  console.log(response);
                });
    }
    }

html部分

          <div class="table">
            <div><p>Team</p></div>
            <div id="app_name"><p>{{ info }}</p></div>

在此处输入图像描述

在此处输入图像描述

标签: javascriptvue.js

解决方案


你必须在里面添加console.log,然后在得到响应后运行

var app = new Vue({
  el: '#app_name',
  data: {
    info: null
  },
   mounted(){
    let league_id=2;
    axios
        .get("https://cors-anywhere.herokuapp.com/https://www.api-football.com/demo/api/v2/leagueTable/" + league_id)
        .then((response)=> {
           this.info = response.data;
          console.log(response.data);  
        });
       
   }
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>



  <div class="table">
   <div><p>Team</p></div>
   
   <div id="app_name">
   <p>{{ info }}</p>
   </div>

你可以得到你的数据response.data


推荐阅读