For a few days I'm having hard time figuring out why I can either use my Laravel API with CORS error message, or not use it at all with 419 CSRF mismatch error.
This is the case: I have a react registration page that sends POST request to http://localhost:8080/api/register, and the route is defined in Laravel in routes/api.php, NOT routes/web.php
At first I tried to follow the docs but got stuck with Error 419: CSRF token mismatch.
This is my axios call from my frontend (register.jsx):
// get CSRF token first
useEffect(() => {
axios.get('http://localhost:8080/sanctum/csrf-cookie').then(response => {
console.log(JSON.stringify(response))
});
}, []);
axios({
method: 'post',
url: 'http://localhost:8080/api/register',
withCredentials: true,
data: {
email: email,
password: password
}
})
.catch (error => {
console.log("Error: ", error.response);
});
I have no idea why it doesn't work, I think i tried all the combinations in the cors.php file and that didn't help.
Also, when I look in the cookies in use in the browser, I did not see the CSRF cookie.
Then I commented out the following line from Kernel.php in the Laravel project (Which is the opposite of what is said in the docs. By default it was commented out, then I uncommented it and now commented again)
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, // <-- This
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
And now it works! I am able to create a user.
But, now there is a new error (although it does create the user):
Access to XMLHttpRequest at 'http://localhost:8080/api/register' from origin 'http://localhost:3000' has >been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested >resource.
Error: undefined
POST http://localhost:8080/api/register net::ERR_FAILED
**I already set 'supports_credentials' => true in cors.php
What should I do?
Thanks