Can't fetch data from API using Vue and Axios
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
-
answered 2020-11-25 06:17
Aliasgher Nooruddin
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)
-
answered 2020-11-25 06:26
garudamon
every data response that requested by axios will wrap in
data
object, so you need to get body data fromdata.body
. you can check byconsole.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))
See also questions close to this topic
-
PHP API for develop website like https://www.betus.com.pa/sportsbook/
I wanted to develop a website like https://www.betus.com.pa/sportsbook/ with the same data and functionality, I tried many APIs but there are some limitations in almost all APIs to get data like a list of sports, spread odds, Moneyline odds, etc.
-
How to get specific value from json api with python
So i have code that gets data from one api but i can only use frist 3 keys like message idk why is that code:
import requests import json result=requests.get('https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2&page=1&offset=1&sort=asc&apikey=mytoken') result.status_code result.text result.json() print (result.json()['message]) # work print (result.json()['gas]) # or any other key dont work
Output from api:
{"status":"1","message":"OK","result":[{"blockNumber":"4620855","timeStamp":"1511634257","hash":"0x5c9b0f9c6c32d2690771169ec62dd648fef7bce3d45fe8a6505d99fdcbade27a","nonce":"5417","blockHash":"0xee385ac028bb7d8863d70afa02d63181894e0b2d51b99c0c525ef24538c44c24","from":"0x731c6f8c754fa404cfcc2ed8035ef79262f65702","contractAddress":"0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2","to":"0x642ae78fafbb8032da552d619ad43f1d81e4dd7c","value":"1000000000000000000000000","tokenName":"Maker","tokenSymbol":"MKR","tokenDecimal":"18","transactionIndex":"55","gas":"3000000","gasPrice":"1000000000","gasUsed":"1594668","cumulativeGasUsed":"4047394","input":"deprecated","confirmations":"7045304"}]}
i can only get status message ect. when i try gas this is error
Traceback (most recent call last): File "main.py", line 11, in print (result.json()[gas]) NameError: name 'gas' is not defined
-
Is there a way to get other user that made a comment data like id, name via facebook graph api from live video comments created in a page?
When I get comments via this: ( using page access token):
https://graph.facebook.com/v9.0/{vidId}/comments?fields=from{name,id},message
I get something like this:
{"data":[ {"from":{"name":"Test","id":"105798558270105"},"message":"test 6","id":"746620259315087_746620639315049"}, {"from":{"name":"Test","id":"105798558270105"},"message":"test 5","id":"746620259315087_746620812648365"}, {"message":"msg 2","id":"746620259315087_746635539313559"}, {"message":"msg 1","id":"746620259315087_746631009314012"}, {"from":{"name":"Test","id":"105798558270105"},"message":"test 4","id":"746620259315087_746630522647394"}, {"from":{"name":"Test","id":"105798558270105"},"message":"test 3","id":"746620259315087_746635205980259"} ],"paging":
comments from user using api are containing "from" section, by comments made by others do not, so I don't know who made a comment.
Maybe some additional permissions are required ?
-
vee validate duplicate messages in other components
i added vee validate in 3 of my seperate components and add messages for them and the messages are not the same but in all of my components they are the same.
<validation-provider v-slot="{ errors }" name="codeNumber" :rules="{ regex: /^\d{6}$/ }" > <v-text-field v-model="codeNumber" :counter="6" :error-messages="errors" label="confirm" required ></v-text-field> </validation-provider>
2
<validation-provider v-slot="{ phoneNumberErrors }" name="phoneNumber" :rules="{ regex: /^09\d{2}\d{3}\d{4}$/ }" > <v-text-field v-model="phoneNumber" :error-messages="phoneNumberErrors" label="phone number" required ></v-text-field> </validation-provider>
-
Pass Javascript Variable to Vue
How can i pass a Javascript Variable to a Vue Component?
I have this jQuery function which generates the menu and pushes all the Values inside the array menu:
var menu = []; $(document).ready(function(){ $('.service-desc-wrap h2,.cta-button').each(function(){ if($(this).hasClass('cta-button')) { if($(this).attr('title') && $(this).attr('href')) { var linkTitle = $(this).attr('title'); var href = $(this).attr('href'); data = [ title = linkTitle, href = href, ] menu.push(data); $('#menu, #menuMobile').append('<a class="menuText" href="'+href+'">'+linkTitle+'</a>') }; } else { var tag = $.slugify($(this).text()); $(this).attr('id',tag); var linkTitle = $(this).text(); if($(this).attr('title')) { var linkTitle = $(this).attr('title'); }; data = [ title = linkTitle, href = tag, ] menu.push(data); $('#menu, #menuMobile').append('<a class="menuText" href="#'+tag+'">'+linkTitle+'</a>') } }); });
I want to pass the array to a Vue Component called
<service-menu-component></service-menu-component>
The jQuery Function and the Component are inside a blade.php file, i'm using Laravel as a backend.
-
Integration of stripe payment in nuxt.js using vue-stripe-checkout npm package
I have a front end application build using nuxt.js and I am trying to integrate stripe payment using vue-stripe-checkout npm package https://www.npmjs.com/package/vue-stripe-checkout. I have followed all the steps as mentioned in the installation guide.
I am facing an error like Window is not defined and I am attaching the error screenshot. I will attached the codes that I have used. Any help is greatly appreciated.
These are the configuration that I have used in
nuxt.config.js
filehead: { script: [ { hid: 'stripe', src: 'https://js.stripe.com/v3/', defer: true } ], }, env: { STRIPE_PK: process.env.STRIPE_PK, }, plugins: [ { src: '~/plugins/stripe-checkout', ssr: false }, ], build: { transpile: [ 'vue-stripe-checkout' ] },
I have created a plugin inside
plugins
folder.import Vue from 'vue'; import { StripeCheckout } from '@vue-stripe/vue-stripe'; export default () => { Vue.component('StripeCheckout', StripeCheckout); };
Index.vue
<script> import StripeCheckout from 'vue-stripe-checkout' export default { components: { StripeCheckout, }, data() { return { publishableKey: process.env.PUBLISHABLE_KEY, payment_method_types: ['card'], items: [ { price_data: { currency: '', product_data: { name: '', images: [ 'imagefile.png', ], }, unit_amount: '', }, quantity: 1, }, ], mode: 'payment', successUrl: '', cancelUrl: '', } }, methods: { checkout() { this.$refs.checkoutRef.redirectToCheckout() } } } </script>
This is my
checkout buttons
<stripe-checkout ref="checkoutRef" :pk="publishableKey" :items="items" :successUrl="successUrl" :cancelUrl="cancelUrl" > <template slot="checkout-button"> <button @click="checkout"> Order Now</button> </template> </stripe-checkout>
-
Access Axios plugin inside Vuex named module
I have axios installed as Vue plugin and want to access it from within a named Vuex store. The axios plugin is defined within
src/plugin/axios.js
as:import Vue from 'vue' import axios from 'axios' export default { install() { Vue.prototype.$http = axios } }
Then in
main.js
I have:import Vue from 'vue' import App from './App.vue' import Axios from './plugins/axios' import router from './router' import { Auth0Plugin } from './auth' import { domain, clientId, audience } from '../auth_config.json' import store from './store/store' Vue.config.productionTip = false Vue.use(Auth0Plugin, { domain, clientId, audience, onRedirectCallback: (appState) => { router.push( appState && appState.targetUrl ? appState.targetUrl : window.location.pathname ) } }) Vue.use(Axios) new Vue({ router, store, render: (h) => h(App) }).$mount('#app')
And the named store is within
store/modules/fixedstations.js
and contains:export const namespaced = true export const state = { authorized: '', listStations: [], dataApi: [], stationsStatus: [], count: 0 } const endpointStationsStatus = 'https://url/rest/api/v1/fixed/status/' export const actions = { // I WANT TO AVOID TO PASS {http}} ---------------- getStationsStatus: async ({ commit },{ http }) => { const { data } = await http.get(endpointStationsStatus) commit('GET_STATIONS_STATUS', data) } } export const mutations = { CHECK_AUTH(state, payload) { state.authorized = payload }, GET_STATIONS_STATUS(state, payload) { state.stationsStatus.push(payload) } }
I want to access Axios http in my actions without having to explicitly pass it when dispatching the action. Currently, in my vue componet, I have to invoke methods as:
methods: { async getData() { // await this.$store.dispatch('fixedstations/increment') await this.$store.dispatch('fixedstations/getStationsStatus', { http: this.$http // WANT TO AVOID TO PASS THIS }) }
I tried using Vue.axios.get (as suggested in post) but this throw error "Vue undefined" ( I added
import Vue from 'vue'
at the beginning ofstore/modules/fixedstations
). Essentially I want to avoid to pass {http:this.$http} whenever I dispatch an action while at the same time avoiding to instantiate multiple instances of axios. -
shipping tab disabled until the billing tab is not right in vue.js
My requirement is I want disabled shipping tab until the billing tab fields are not valid or error in any field and the checkbox is also disabled until all field is not right in the billing tab, I am using one form for both sections. There must be one probability when the user filled all the billing section filed and go to the shipping tab and again come back to the billing section and make any error in this condition check box is disabled and uncheck and shipping tab is also disabled. I am using this appraoch.
<validation-observer v-slot="{ invalid, handleSubmit }"> <form name="Address" @submit.prevent="handleSubmit(onSubmit)"> <!-- BILLING/SHIPPING TABS --> <v-tabs v-model="selectedTab"> <v-tab> <h3 class="tab">TAB Billing</h3> </v-tab> <v-tab v-bind:disabled="invalid? isDisabledCheckbox(): isDisabledTab" > <h3 class="tab">TAB Shipping</h3> </v-tab> <!-- BILLING TAB --> <div class="flex xs12 sm5"> <validation-provider v-slot="{ errors }" rules="required"> <label for="Name">Name</label> <input name="Name" v-model="Name" class="form-control" id="Name"type="text"> <span class="error--text">{{ errors[0] }}</span> </validation-provider> </div> <!-- Billing Street --> <validation-provider v-slot="{ errors }" :rules="{ required: Address }"> <label class="font-weight-bold mx-0 mb-2" for="Address">Address</label> <input v-model="Address" name="Address" class="form-control" id="Address" type="text"> <span class="error--text">{{ errors[0] }}</span> </validation-provider> <validation-provider vid="shippingChecked"> <label> <input v-bind:disabled="obj.shipping.shippingChecked == true? false: invalid" id="ShippingAndBillingIsNotSame" @change="ShippingAndBillingIsNotSame" v-model="obj.shipping.shippingChecked" type="checkbox" value="true"> <span for="">Billing and shipping is not same</span> </label> </validation-provider> <!-- END BILLING TAB --> <!-- SHIPPING TAB --> <template v-if="obj.shipping.shippingChecked == true" > <div class="px-3 layout row wrap"> <div class="flex xs12 sm5"> <validation-provider v-slot="{ errors }" rules="required"> <label for="Name">Name</label> <input name="Name" v-model="Name" class="form-control" id="ship-to-forename" type="text"> <span class="error--text">{{ errors[0] }}</span> </validation-provider> </div> </form> </validation-observer> data: function () { return { isDisabledTab: true, selectedTab: '1' } }, methods: { ShippingAndBillingIsNotSame: function () { if (this.obj.shippingInfo.shippingChecked==true) { this.isDisabledTab = false; this.selectedTab = 1; } }, isDisabledCheckbox: function () { let test = false; if (this.selectedTab != 1) { this.obj.shippingInfo.shippingChecked = false; this.isDisabledTab = true; test = true; } return test; }, }
This approach is not working when I come back from the shipping tab in the billing tab the check box is disabled when the shipping section has an error. Is there any Inbuild approach or any other functionality?
-
How to add a module getters in composition api?
I am using vue 2, installed composition api. How can I add Getters? Usually:
computed: { ...mapGetters("Auth", ["isLogged"])}
..........................................................................
setup() { const title_app = ref("Name App"); const logout = () => { store .dispatch("Auth/logout") .then(() => { router.push({ name: "About" }); }) .catch((err) => { console.log(err); }); }; return { title_app, logout, };
},
-
Cloudflare API Update DNS using Axios
I'm trying to update my DNS IP in Cloudflare via API.
Developing in NodeJS, I'm using Axios instead of BSH curl command as described in the Cloudflare API Documentation.
When I'm using the BSH command in my Terminal it works, so I'm sure that my token, and other settings are correct.
In my opinion, it comes from Axios syntax that I'm not using properly.
In Cloudflare API documentation, the commands are described as following:
curl -X PUT "https://api.cloudflare.com/client/v4/zones/<zone token>/dns_records/<dns id>" \ -H "X-Auth-Email: user@example.com" \ -H "X-Auth-Key: <token api>" \ -H "Content-Type: application/json" \ --data '{"type":"A","name":"example.com","content":"127.0.0.1","ttl":1,"proxied":true}'
I translated that command using Axios as following, but it's not working. I got a 400 error.
const UpdateDNSCloudflare = async() =>{ let res = await axios.put('https://api.cloudflare.com/client/v4/zones/<zone token>/dns_records/<dns id>', { headers:{ 'X-Auth-Key':'<token api>', 'X-Auth-Email':'user@example.com', 'Content-Type':'application/json' }, data:{ 'type' : 'A', 'name' : 'example.com', 'content': '127.0.0.1', 'ttl': 1, 'proxied': true }, }); console.log(res); return res; }
Error message:
(node:78276) UnhandledPromiseRejectionWarning: Error: Request failed with status code 400
Does someone can help me?
-
TypeError while looping on the response
I am getting Error :
TypeError: Cannot read property 'url' of undefined
while I am looping on the response like this :
getPhoto = (venueId) => { const PhotoEndpoint = `https://api.foursquare.com/v2/venues/${venueId}/photos?`; const parameters = { client_id: "my client_id", client_secret: " my client_secret", group: "venue", limit: "100", v: "20211301", }; axios .get(PhotoEndpoint + new URLSearchParams(parameters)) .then((response) => { for (var i = 0; i < response.data.response.photos.items.length; i++) { this.setState({ photosUrl: response.data.response.photos.items[i].prefix + "original" + response.data.response.photos.items[i].suffix, }); } }) .catch((error) => { console.log(" My photo Error : " + error); }); };
and the data I am receiving is like this: https://foursquare.com/developers/explore#req=venues%2F43695300f964a5208c291fe3%2Fphotos%3F
or I just paste it here as well in case the link didn't work:
{ data: { meta: { code: 200, requestId: "6002bcf5c8ba5b3c6d668965", }, notifications: [{ type: "notificationTray", item: { unreadCount: 5, }, }, ], response: { photos: { count: 30, items: [{ id: "51b8f916498e6a8c16a329eb", createdAt: 1371076886, source: { name: "Instagram", url: "http://instagram.com", }, prefix: "https://fastly.4sqi.net/img/general/", suffix: "/26739064_mUxQ4CGrobFqwpcAIoX6YoAdH0xCDT4YAxaU6y65PPI.jpg", width: 612, height: 612, user: { id: 26739064, firstName: "Darius", lastName: "Alonzo", gender: "male", countryCode: "US", photo: { prefix: "https://fastly.4sqi.net/img/user/", suffix: "/BWWLKDFKJ4VOVFXK.jpg", }, }, checkin: { id: "51b8f915498e481c2e86de41", createdAt: 1371076885, type: "checkin", timeZoneOffset: -240, }, visibility: "public", }, ], }, }, } };
There would be more than 100s of items. I am trying to get the prefix to concatenate it with the size which is original and again concatenate suffix to make a URL, and
setState
my PhotoUrl and later render each photo but I am getting TypeError What I am doing wrong?