axios typeError: Невозможно установить свойство 'username' из неопределенного - PullRequest
0 голосов
/ 17 сентября 2018

Когда я использовал POSTMAN для тестирования бэкэнд-API, все прошло правильно, и данные ответов выглядели так: {"username":"123","email":"123@gmail.com"}.Затем я использовал axios для получения данных:

<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>

Но произошла ошибка typeError: Cannot set property 'username' of undefined.Я запутался в этом.Может ли кто-нибудь помочь?

1 Ответ

0 голосов
/ 17 сентября 2018

здесь следует использовать arrow function in es6 instead of function (), например

: (response)=>{ вместо 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);
        });
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...