2

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() }}">
4
  • did you check does X-CSRF-TOKEN is passed to BE? Commented Sep 29, 2020 at 8:06
  • check this one github.com/axios/axios/issues/2024 Commented Sep 29, 2020 at 8:11
  • @vaske If I look in the Network tab I see the CSRF token but still a 419 error code. Screenshot Commented Sep 29, 2020 at 9:01
  • I would then debug BE side, usually 419 error means that its expired Commented Sep 29, 2020 at 10:08

1 Answer 1

0

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)
    }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.