在vue.js中使用axios打印来自HTTP GET请求的响应? [英] Print response from http GET request using axios in vue.js?
问题描述
当我访问 https://jsonplaceholder.typicode.com/todos?_limit=1 在我的浏览器中,我得到:
When I access https://jsonplaceholder.typicode.com/todos?_limit=1 in my browser I get:
[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
]
我现在正在尝试使用具有上述URL的vue.js中的axios将简单的http GET请求的结果(和打印结果)存储在变量中:
I am now trying store the result (and print) of a simple http GET request in a variable using axios in vue.js with the above URL:
const result = axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
console.log("result is = " + result)
console.log("result.title is = " + result.title)
但是上面给出了以下输出:
But the above gives the below output:
App.vue?234e:59 result is = [object Promise]
App.vue?234e:60 result.title is = undefined
是否无需处理vue.js中的 promises
,就不可能从http get请求(如curl)打印json友好的结果?
Is it not possible to print a json friendly result from a http get request (like with curl) without having to deal with promises
in vue.js?
更新:
基于以下答案,我现在已经在我的 App.vue 文件中尝试了以下操作
Based on below answers I have now tried the following in my App.vue file
<script>
import axios from 'axios';
export default {
name: 'app',
components: {
AddTodo
},
data(){
return {
todos: []
}
},
methods: {
// not allowed to use function keyword here
async printJson(){
let result = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
console.log("result is = " + result)
console.log("result.title is = " + result.title)
},
addTodo(newTodo) {
this.printJson()
}
}
}
</script>
但这只是给出了:
App.vue?234e:50 result is = [object Object]
App.vue?234e:51 result.title is = undefined
推荐答案
找到答案的依据是:
实际上非常简单,我只需要使用 JSON.stringify(data)
:
actually very simply I just need to use JSON.stringify(data)
:
async printJson(){
let result = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
let data = result.data
let pretty = JSON.stringify(data)
console.log("Pretty = " + pretty)
},
给出:
App.vue?234e:54 Pretty = [{"userId":1,"id":1,"title":"delectus aut autem","completed":false}]
这篇关于在vue.js中使用axios打印来自HTTP GET请求的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!