首页 > 解决方案 > 从rest api vue中获取

问题描述

我可能有点愚蠢 :) 但是我已经复制粘贴了数百个解决方案 noee 并尝试了我能想到的一切(我对 VUE 和 JS 完全陌生,所以请善待:))

这是我现在拥有的代码。我可以看到它在 F12 中获取数据,但我无法将数据放入可以在函数外部使用的变量中。

我想对我的数据做一些 reponseDataToSession.user.name 等等,或者循环遍历一些数据,但是如果我在我的 fetch 之外使用 console.log,我会得到空或什么都没有。

请帮助我让我的代码整天都在这个小东西上工作。

我得到的错误是:ReferenceError:reponseDataToSession 未定义

所以这里是代码。

 <template>
    <div id="app">
        <input
                v-model="sessionUUID"
                @keyup.enter="fetchsessions()"
                name="search"
                type="text"
        />

        <input
                @mouseup="fetchsessions()"
                name="serchSubmit"
                value="SÖK"
                type="submit"
        />

        <template v-if="viewData">
            {{responseDataToSession}}
        </template>
    </div>
</template>


<script>
import base64 from "base-64";

export default {
  name: "App",
  data() {
    return {
      sessionUUID: "",
        responseDataToSession: {},
      viewData: false,
    };
  },
  methods: {
    fetchsessions: function () {
      const url = "http://localhost:8080/gethistory";
      const method = "POST"
      const username = "user";
      const password = "bass";
      const body = JSON.stringify({"uuid": "' + this.sessionUUID + '","answers": []});       
      const headers = new Headers();

      headers.append("Content-Type", "application/json");
      headers.append("Authorization", "Basic " + base64.encode(username + ":" + password));
      
      this.responseDataToSession = fetching();
      console.log("1"+this.reponseDataToSession)
      this.viewData = true

      async function fetching() {
        return this.responseDataToSession = await fetch(url, { method, headers, body });
      }

    }
  }
};
</script>

  

标签: vue.jsasync-awaitfetchundefined

解决方案


你有一个ReferenceError: response is not defined因为你必须在之前声明你的变量响应。所以你应该写:

async function fetching() {
        const  response = await fetch(url, { method, headers, body });
        return response
      }

或者直接(如果您的变量“响应”仅适用于您不需要的功能)

async function fetching() {
        return await fetch(url, { method, headers, body });
      }

对于responseDataToSession, 尝试使用responseDataToSession: {},


推荐阅读