Getting axios to pull data for a simple script

I’m trying to pull from an API but the error keeps popping up

Error in created hook: “TypeError: this.$appName.get is not a function”

index.html

<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <div id="example">
    <h2>{{ product }}</h2>
    <p>{{ description }}</p>
    <p>{{ info }} </p>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="js/main.js"></script>
</html>

main.js

Vue.prototype.$appName = ‘axios’

new Vue({
el: ‘#example’,
data: {
product: “Website”,
description: “This is my website”,
info: null
},
beforeCreate: function() {
console.log(this.$appName)
},
created() {
this.$appName
.get(‘https://api.coindesk.com/v1/bpi/currentprice.json’)
.then(response => (this.info = response))
}

})

Have also tried this, but didn’t work

new Vue({
el: ‘#example’,
data: {
product: “Website”,
description: “This is my website”,
info: null
},
mounted {
axios
.get(‘https://api.coindesk.com/v1/bpi/currentprice.json’)
.then(response => (this.info = response))
}

})

Hi

You need to load axios in your html. Exactly the same way as you loads vue:

<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <div id="example">
    <h2>{{ product }}</h2>
    <p>{{ description }}</p>
    <p>{{ info }} </p>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.1/axios.js"></script>
  <script src="js/main.js"></script>
</html>

and then can you use axios.get(), axios.post() and so on

new Vue({
	el: '#example',
	data: {
		product: 'Website',
		description: 'This is my website',
		info: null
	},
	created() {
		axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
			.then(response => {
				console.log(response)
				this.info = response
			})
	}
})
1 Like

Thank you. This is very helpful.

1 Like