#POST request from React to Laravel. CORS troubles. 419 Error Code

9 messages · Page 1 of 1 (latest)

sharp tiger
#

Hello everyone! Please help, I encountered a problem, when I send a request to create a new user to the server from React, I get the following error: Request failed with status code 419. Whatever I did, nothing helps, I saw information on the Internet about changing headers, but it didn't help me, maybe I'm doing something wrong... I use React Query and *Axios*I would be very grateful!

In my AuthController method register:

public function registered(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $user->assignRole('admin');

        $token = $user->createToken('main')->plainTextToken;

        event(new Registered($user));

        Auth::login($user);

        return response([
            'user' => $user,
            'token' => $token,

        ]);
    }

And my query:

export const useLogin = () => {
    // const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    // console.log(csrfToken)
    return useMutation(
        'reg',
        (formData) => {
            return axiosClient.post('/registered', formData)
            .then(res => res.data)
            .catch(err => {
                console.log(err)
            })
            
        }
    )
}

AxiosClient:

import axios from "axios";

const axiosClient = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL
})

// axiosClient.defaults.withCredentials = true


axiosClient.interceptors.request.use((config) => {
    const token = '123sdfsdfsd4'
    config.headers.Authorization = `Bearer ${token}`
    return config
})

axiosClient.interceptors.response.use(response => {
    return response
})

export default axiosClient

If I comment // \App\Http\Middleware\VerifyCsrfToken::class, it works, but I think it's wrong way

#

POST request from React to Laravel. CORS troubles. 419 Error Code

#

I added this in my VerifyCsrfToken

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

Maybe is it the right way?

#

and it works

surreal willow
#

Yep, that's the correct way to disable CSRF protection on the API

#

But also, if you are using Sanctum (https://laravel.com/docs/10.x/sanctum#main-content) - you can retain the CSRF and you won't have to manage an auth token. It might not be best for your use case so double check 🙂

I've pretty much always disabled CSRF by adding API to the exceptions list

Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.

tacit shadow
surreal willow
#

@tacit shadow Should've been more clear - Sanctum is the only one that I keep CSRF on for 🙂 It is indeed a very bad idea to disable it for SPA authentication