1
votes

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?

1
I got it. It the this thing. this in this.username = response.data['username']; doesn't point to Vue intstance but undefined. Use arrow function instead of function (response) { //... } .maxwellhertz
Unless you're using transpilers, arrow functions will give problems to older browsers or shittier ones cough ie11 cough. It's safer to just declare this on a variable at the top of the method and use that variable instead.Abana Clara

1 Answers

0
votes

you should use the arrow function in es6 instead of function () in here,

example: (response)=>{ instead of function(response){

methods: {
      getInfo () {
          axios.get('http://localhost:8088/api/information')
          .then((response)=> {
              this.username = response.data['username'];
              this.email = response.data['email'];
              console.log(response);
        })
        .catch(function (error) {
              console.log(error);
        });
    }
}