简体   繁体   中英

CSRF token mismatch with Laravel SPA Application

I've made a Laravel SPA application with Vue and Laravel Sanctum, but every time I do a POST request with axios I get a 419 error code (CSRF code mismatch).

My bootstrap.js

window._ = require('lodash');
window.axios = require('axios');
window.axios.defaults.withCredentials = true;
window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
};
axios.get('/sanctum/csrf-cookie').then(response => {
                    console.log(response);
                    axios.post('/api/auth/login', this.fields).then(response => {
                        this.disabled = false;
                        router.push({ name: 'client.index' });
                    }).catch(error => {
                        this.disabled = false;
                        if(error.response.status === 401) {
                            this.errors.email = 'Your given credentials are incorrect';
                        } else {
                            this.errors.email = (!error.response.data.errors.email) ? '' : error.response.data.errors.email[0];
                            this.errors.password = (!error.response.data.errors.password) ? '' : error.response.data.errors.password[0];
                        }
                    });
                });

In my head I've already placed the meta tag with the CSRF code.

    <meta name="csrf-token" content="{{ csrf_token() }}">

You can intercept http status 419 (non standard status defined by Laravel) and reload the page to generate a new CSRF token :

axios.interceptors.response.use(
    response => response.data,
    error => {
        if (error.response && 419 === error.response.status) {
            window.location.reload()
        }

        return Promise.reject(error)
    }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM