Print Response From Http Get Request Using Axios In Vue.js?
Solution 1:
Well thats not the way to do it...
Here are few ways to do it:
(asyncfunction(){
const result = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
console.log("result is = " + result.data)
console.log("result.title is = " + result.data.title)
})()
or the old way like this:
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1').then(function(result){
console.log("result is = " + result.data)
console.log("result.title is = " + result.data.title)
})
Solution 2:
Yeah most of us do not want to deal with promises. Which is why the new JavaScript added async and await keywords.
functioncall(){
return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
}
asyncfunctionprintJson(){
let result = awaitcall();
console.log("result is = " + result)
console.log("result.title is = " + result.title)
}
I pulled your call in a separate function to highlight the await better. I think it is not required (but cleaner in either case).
Technically there is still the promise, but you do not deal with it; Javascript does now. There is also a ton of information out there about async and await. As you can imagine, a lot of people want to get away from infinitely stacked callbacks.
UPDATE
I have run this through a fiddle now myself and the code works, once the access is adjusted to the structure of the returning JSON, which is an array of objects.
See this fiddle https://jsfiddle.net/xb2fck19/1/
Also you can put functions in the vue methods like this
<script>import axios from'axios';
//Version 1 - private functionfunctioncall(){
return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
}
exportdefault {
name: 'app',
components: {
AddTodo
},
data(){
return {
todos: []
}
},
methods: {
// not allowed to use function keyword here asyncprintJson(){
//make this.call(); if using version 2let result = awaitcall();
let data = result.data;
console.log(data);
for (let entry of data){
console.log("result is = " + entry)
console.log("result.title is = " + entry.title)
}
},
//Version 2 - public functioncall(){
return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
}
addTodo(newTodo) {
this.printJson()
}
}
}
</script>
Solution 3:
Axios returns Promise always so you can use then()
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1').then(response => { console.log(response); }
Solution 4:
Found the answer based on:
actually very simply I just need to use JSON.stringify(data)
:
asyncprintJson(){
let result = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
let data = result.datalet pretty = JSON.stringify(data)
console.log("Pretty = " + pretty)
},
which gives:
App.vue?234e:54 Pretty = [{"userId":1,"id":1,"title":"delectus aut autem","completed":false}]
Post a Comment for "Print Response From Http Get Request Using Axios In Vue.js?"