M
M
Mikhail Smirnov2018-10-22 20:30:42
Vue.js
Mikhail Smirnov, 2018-10-22 20:30:42

How to catch 401 error in vuejs and Yii2?

Good evening!
I use axios.interceptors.response to catch errors in the server response, the
problem is that the error comes but console.log(error) displays undefined

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {

    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;

    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
        // Do something with response data
        return response;
    }, function (error) {
        
        console.log(error)
        
        return Promise.reject(error);
    });

} else {
    console.error('CSRF token not found');
}

If you track errors directly in the request, then everything is fine
axios({
                        method: 'post',
                        url: '/api/login',
                        responseType: 'json',
                        data: {
                            phone: this.phone,
                            password: this.password,
                            rememberMe: this.remember_me
                        }
                    }).then((response) => {
                        this.refreshCSRFToken(response.data.token);
                        if (response.data.result == 'success') {
                            this.is_logged_in = true;
                            this.current_user = response.data.user_id;
                        } else {
                            if (response.data.messages.password) {
                                this.password_error = response.data.messages.password;
                            }
                            if (response.data.messages.phone) {
                                this.login_error = response.data.messages.phone;
                            }
                        }
                    })
                    .catch(function (error) {
                            console.log(error);
                    });

api service on the same domain on Yii2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad, 2018-10-23
@progress_man

Mikhail Smirnov , try to withdraw console.log(error.response)or console.log(JSON.stringify(error))instead of console.log(error). Perhaps the problem will be solved. If you doubt the adequacy of my answer, you can read here ;-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question