简体   繁体   English

在 vue.js 中使用 axios 打印来自 http GET 请求的响应?

[英]Print response from http GET request using axios in vue.js?

When I access https://jsonplaceholder.typicode.com/todos?_limit=1 in my browser I get:当我在浏览器中访问https://jsonplaceholder.typicode.com/todos?_limit=1 时,我得到:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  }
]

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:我现在正在尝试使用 vue.js 中的 axios 将一个简单的 http GET 请求的结果(和打印)存储在一个变量中,并使用上述 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

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?是否无法从 http get 请求(如 curl)打印一个 json 友好的结果而不必处理 vue.js 中的promises

UPDATE:更新:

Based on below answers I have now tried the following in my App.vue file基于以下答案,我现在在我的App.vue文件中尝试了以下内容

<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>

But that just gives:但这只是给出:

App.vue?234e:50 result is = [object Object]
App.vue?234e:51 result.title is = undefined

Well thats not the way to do it...嗯,这不是这样做的方式......

Here are few ways to do it:以下是几种方法:

(async function(){
   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)
})

Yeah most of us do not want to deal with promises.是的,我们大多数人都不想处理承诺。 Which is why the new JavaScript added async and await keywords.这就是新 JavaScript 添加asyncawait关键字的原因。

function call(){
  return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
}

async function printJson(){
  let result = await call();
  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. Javascript 现在可以了。 There is also a ton of information out there about async and await.还有大量关于 async 和 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.我自己现在已经通过一个小提琴来运行它并且代码工作,一旦访问被调整为返回的JSON的结构,它是一个对象数组。

See this fiddle https://jsfiddle.net/xb2fck19/1/看到这个小提琴https://jsfiddle.net/xb2fck19/1/

Also you can put functions in the vue methods like this你也可以把函数放在像这样的 vue 方法中


<script>

import axios from 'axios';

//Version 1 - private function
function call(){
  return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
}

export default {
  name: 'app',
  components: {
    AddTodo
  },
  data(){
    return {
      todos: []
    }
  },

  methods: {
    // not allowed to use function keyword here  
    async printJson(){
      //make this.call(); if using version 2
      let result = await call();
      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 function
    call(){
      return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
    }
    addTodo(newTodo) {
      this.printJson()  
    }
  }
}
</script>

Axios returns Promise always so you can use then() Axios 总是返回 Promise,所以你可以使用 then()

axios.get(' https://jsonplaceholder.typicode.com/todos?_limit=1 ').then(response => { console.log(response); } axios.get(' https://jsonplaceholder.typicode.com/todos?_limit=1 ').then(response => { console.log(response); }

Found the answer based on:根据以下内容找到答案:

Show json result with vue.js 使用 vue.js 显示 json 结果

actually very simply I just need to use JSON.stringify(data) :实际上非常简单,我只需要使用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)
},    

which gives:这使:

App.vue?234e:54 Pretty = [{"userId":1,"id":1,"title":"delectus aut autem","completed":false}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM