1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Laravel 11 CSRF Token Mismatch Error on API Registration

Discussão em 'Outras Linguagens' iniciado por iseiaki, Outubro 10, 2024 às 11:42.

  1. iseiaki

    iseiaki Guest

    I'm currently developing a Laravel 11 application with a React front-end, and I'm running into a persistent "CSRF token mismatch" error when attempting to register a user via the API. I have tried several methods to resolve this issue but haven't had any success.

    Details:

    I have a form in my React application that sends user registration data to my Laravel backend. Here’s the relevant code for my Register component:
    import React, { useState } from 'react';
    import axios from 'axios';

    export default function Register() {
    const [formData, setFormData] = useState({
    first_name: '',
    last_name: '',
    email: '',
    password: '',
    });

    const handleChange = (e) => {
    setFormData({
    ...formData,
    [e.target.name]: e.target.value,
    });
    };

    const handleSubmit = async (e) => {
    e.preventDefault();

    // Get CSRF token from the meta tag
    const csrfTokenMeta = document.head.querySelector('meta[name="csrf-token"]').content;

    if (csrfTokenMeta) {
    console.log('CSRF Token:', csrfTokenMeta);
    } else {
    console.error('CSRF Token meta tag not found.');
    }

    try {
    const response = await axios.post('http://localhost:8000/api/register', formData, {
    headers: {
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': csrfTokenMeta, // Include CSRF token
    },
    });

    alert('User registered successfully!');
    console.log(response.data);
    } catch (error) {
    console.error('Registration error:', error);
    alert('Error registering user. Please try again.');
    }
    };

    return (
    <form onSubmit={handleSubmit}>
    {/* Form fields for first name, last name, email, and password */}
    </form>
    );
    }

    Problem:

    When I submit the form, I receive the following error:
    {message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException"}

    What I’ve Tried:

    CSRF Token Verification:
    I've ensured the CSRF token is being correctly fetched and sent in the request headers. Session Configuration:

    Verified that config/session.php is set to use the file driver and same_site is set to lax. CORS Configuration:

    Updated config/cors.php to ensure the API endpoint is included:

    'paths' => ['api/*'],
    'allowed_origins' => ['*'],

    Inspect Network Requests

    Checked the network requests in the browser's developer tools and confirmed that the CSRF token is being sent correctly in the headers.

    Cleared Cache


    php artisan config:cache
    php artisan route:cache
    php artisan cache:clear

    CSRF token initialization


    In my app.blade.php, I included the CSRF token like this:

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

    Continue reading...

Compartilhe esta Página