How to correctly send the CSRF token with Axios, React and Laravel 9. Request failed with status code 419

1.6k views Asked by At

I'm using React, Inertia, Breeze and Laravel 9. When sending a request to the server with Axios, I get the following error: `{message: 'Request failed with status code 419', name: 'AxiosError', code: 'ERR_BAD_REQUEST'.

My code is the following (React):

const handleLogout = (e) => {
      e.preventDefault();
      const token = document.head.querySelector('meta[name="csrf-token"]').getAttribute('content');
      console.log(token);
      axios.post('logout', { name: 'John Doe' }, {
          headers: {
          'content-type': 'text/json',
          'X-CSRF-TOKEN': token
          }
      }
      );
    }; 

and in my HTML I have:

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

It correctly prints the token in console.log but throws me the error. Something when passing the token does not work for me.

0

There are 0 answers