0

I have a React project and a seperate Laravel project, which communicate with eachother. But whenever I send a POST-request from React to Laravel, it gives me a CSRF Token Mismatch. Now if the form was inside my Laravel project, I could just add the token as a field in my form, but it's a seperate project so I'm not sure.

I tried to add the token in resources/js/bootstrap.js, because I'm using Axios. I changed the code to:

import axios from 'axios';

window.axios = axios;
window.Laravel = {csrfToken: '{{ csrf_token() }}'};

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;

But it still doesn't work, how can I handle this?

1 Answer 1

1

First of all csrf work with web.php by default. So when you write a post request route within the web.php route file then you'll face csrf token problem.

Solution 1:

Whenever you're writing Rest APIs for SPA's or mobile apps. You should use api.php route file. Because in the api.php route file, some layers are excluded due to their stateless behavior.

If you use api.php route file then you don't need to send csrf token in request headers.

Solution 2:

if you're writing API in web.php then you need to add that route in App\Http\Middleware\VerifyCsrfToken middleware except array, like following:

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
    ];
}

In this way, that route will not throw csrf related errors.

I hope that will helps you.

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.