When I used POSTMAN to test the backend API, everything went right and the response data looked like:
{"username":"123","email":"123@gmail.com"}
. Then I used axios to get the data:
<template>
<div>
<h1>Welcome!</h1>
<div>
<b-button @click="getInfo()">Get your information</b-button>
<h2 v-if="username !== ''">Your username is: {{ username }}</h2>
<h2 v-if="email !== ''">Your email is: {{ email }}</h2>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
username: '',
email: ''
}
},
methods: {
getInfo () {
axios.get('http://localhost:8088/api/information')
.then(function (response) {
this.username = response.data['username'];
this.email = response.data['email'];
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>
But there was an error typeError: Cannot set property 'username' of undefined
. I am confused about it. Could anyone help?
this
thing.this
inthis.username = response.data['username'];
doesn't point to Vue intstance butundefined.
Use arrow function instead offunction (response) { //... }
. – maxwellhertzthis
on a variable at the top of the method and use that variable instead. – Abana Clara