I am new to API design and I am trying to implement an API call that simply displays data from an API server I found online using the vue.js project via CLI. Though I am able to see the results in the console of the browser, I am not able to see the actual data display on the webpage I am working on. I have seen similar questions like mine, but none of those seem to have the same issues I am, using Vue. After spending a few days researching, I just can't seem to find the issue and I am pretty sure it is a pretty fundamental thing I am messing up, which makes it even more frustrating to admit defeat on this. Here is the code in question:
<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>
Here are the results I get in my console for the code:
Can anyone identify what I am doing wrong? Thank you very much.
you does not set any response
data yet, in your response
data property. Instead of call API
directly in mounted()
, you can call this API
in methods from mounted()
. This is good coding. Exactly, how it is works:
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();
}
}
Thanks.