TransWikia.com

Can't fetch data from API using Vue and Axios

Stack Overflow Asked by Via on December 31, 2020

I’m creating an e-learning website where there are cards of courses that you can pick. Here are my codes

<template>
<div>
  <v-container>
      <v-row>
          <v-col md="3" offset-lg="1">
              <Categories />
          </v-col>
          <v-col md="9" lg="7">
              <CourseList v-bind:list="list"/>
          </v-col>
      </v-row>
  </v-container>
</div>
</template>

<script>
import CourseList from '@/components/courses/CourseList.vue'
import Categories from '@/components/courses/Categories.vue'
import axios from 'axios'


export default {
  components: {
    CourseList,
    Categories
  },
  data() {
         return {
            list: []
         }
  },
  mounted: function() {
            axios
                .get('https://esl3usx3t7.execute-api.us-east-1.amazonaws.com/testing1/api/get_course')
                .then(res => this.list = res.body)
                .catch(err => console.log(err))
        }
}
</script>

CourseList.vue

<template>
  <div>
      <h2>Courses</h2>

      <v-row>
          <v-col sm="6" md="4">
              <VerticalCard v-bind:list="list"/>
              
          </v-col>
      </v-row>
      
  </div>
</template>

<script>
import VerticalCard from '@/components/cards/VerticalCard.vue'

export default {
    name: "CourseList",
    components: {
        VerticalCard
    },
    props: ["list"]
}
</script>

My problem is I haven’t been able to fetch the data from API link ->
https://esl3usx3t7.execute-api.us-east-1.amazonaws.com/testing1/api/get_course

I wonder what am I doing wrong. I have also tried to use {{list}} to get the data, but it didn’t work. My goal right now is to get all the data even though it will look messy. Sorry for my bad English and thank you!

2 Answers

axios wraps data in data object so instead of .then(res => this.list = res.body)it should be.then(res => this.list = res.data.body)

Correct answer by Aliasgher Nooruddin on December 31, 2020

every data response that requested by axios will wrap in data object, so you need to get body data from data.body. you can check by console.log(res)

const uri = 'https://esl3usx3t7.execute-api.us-east-1.amazonaws.com/testing1/api/get_course'
axios
  .get(uri)
  .then(res => {
    console.log(res)
    let {data: {statusCode, body}} = res
    if(statusCode == 200)
      this.list = [...body]
  })
  .catch(err => console.log(err))

Answered by garudamon on December 31, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP