![](/img/trans.png)
[英]Node.js + Vue.js: why is console.log() in vue.js files not showing in console?
[英]API data is showing in the browser's console but not on the webpage - Vue.js
我是 API 设计的新手,我正在尝试实现一个 API 调用,它只显示来自我通过 CLI 使用 vue.js 项目在线找到的 API 服务器的数据。 虽然我能够在浏览器的控制台中看到结果,但我无法在我正在处理的网页上看到实际数据显示。 我见过类似的问题,但使用 Vue 似乎没有一个问题与我相同。 在花了几天的时间研究之后,我似乎无法找到问题所在,我很确定这是我搞砸的一个非常基本的事情,这使得承认失败更加令人沮丧。 这是有问题的代码:
<template>
<div class="health">
<p>{{response}}</p>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "HelloHealth",
data() {
return {
response: ""
};
},
mounted() {
axios({
method: "GET",
url:
"https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random",
headers: {
"content-type": "application/octet-stream",
"x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
"x-rapidapi-key": "5788793819msh9c9b16c2298d826p1e5fefjsn3d5bde507db6",
accept: "application/json"
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
};
</script>
以下是我在控制台中获得的代码结果:
谁能确定我做错了什么? 非常感谢。
您尚未在response
数据属性中设置任何response
数据。 您可以在 mount mounted()
) 的方法中调用此API
,而不是直接在mounted()
中调用API
。 这是很好的编码。 确切地说,它是如何工作的:
import axios from "axios";
export default {
data() {
return {
response: ""
}
},
methods: {
getResponseData() {
axios({
method: "GET",
url:
"https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random",
headers: {
"content-type": "application/octet-stream",
"x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
"x-rapidapi-key": "5788793819msh9c9b16c2298d826p1e5fefjsn3d5bde507db6",
accept: "application/json"
}
})
.then(response => {
this.response = response.data;
console.log(this.response); //get response data
})
.catch(error => {
console.log(error);
});
}
},
mounted() {
this.getResponseData();
}
}
谢谢。
您没有将this.response
设置为""
以外的任何内容。 在你的mounted()
调用中,Axios调用成功后,你需要设置响应:
.then(response => {
this.response = response.data;
})
Vue 的文档在此处提供了关于使用 API 和将数据集成到 Vue 的非常好的指南: https ://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html
.then(response => {
this.response = response.data;
console.log(this.response); //get response data
})
axios 返回的响应有不同的范围。 它仅在 then 功能中可用。 您应该将组件的响应设置为 axios 返回的响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.