VueJS Get CSRF Token in Axois Post

axios.post('/url', {
    _token: document.querySelector('meta[name="csrf-token"]').content;
}).then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

In order to use the CSRF token in an Axios VueJS post, you will first need to make sure that in your HTML you have the CSRF meta tag like so:

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

Then, when you want to retrieve it from your javascript file you will want to create a global window variable like so:

window.csrfToken = document.querySelector('meta[name="csrf-token"]').content;

Now, we can use the csrfToken inside of our Axios Post:

axios.post('/url', {
    _token: csrfToken
}).then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

Easy enough :)

BETA Snippet explanation automatically generated by OpenAI:

No explanation generated yet.

Snippet By Dev Dojo

·

Created June 12th, 2021

·

Report Snippet