Ad

Laravel Is Csrf_field() Needed In Form When Using Axios

- 1 answer

I wonder if I need to include {{ csrf_field() }} inside my <form> when I do a ajax post request on that form using Axios.

In my bootstrap I already setup some kind of csrf protection like this:

//Add headers to axios
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
  window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
  console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

// html

<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
Ad

Answer

No, when you're adding the CRSF-token to the axios headers, there's no need to include crsf_field in the form. It's appended on all headers, as it's already added to axios default headers.

Ad
source: stackoverflow.com
Ad