1

Hi im trying to do a app using react as front-end and laravel 12 as api doing AJAX requests i can create users from bruno but when i trying with my react app i always receive the following CORS error:

Access to fetch at 'http://localhost:5173/' (redirected from 'http://127.0.0.1:8000/api/users') from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

this is my cors.php file:

<?php

 return [

'paths' => ['api/*', 'sanctum/csrf-cookie'],


'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false,

];

this is my react file:

import { useState } from "react";

//id, username, password, nombre, apellidos, tipo_usuario y activo
const register = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState('');
const [name, setName] = useState('');
const [lastname, setLastname] = useState('');

const checkValues = () => {
    let mensaje = '';

    if (!username) {
        mensaje += 'username*\n'
    }

    if (!password) {
        mensaje += 'password*\n'
    }

    if (!confirm) {
        mensaje += 'confirm password*\n'
    }

    if (!name) {
        mensaje += 'Nombre*\n'
    }

    if (!lastname) {
        mensaje += 'lastname*\n'
    }

    if (mensaje) {
        mensaje = 'Los siguientes campos son obligatorios:\n' + mensaje;
        alert(mensaje)
        return false;
    }

    if (!password === confirm) {
        alert('Las contraseñas no son iguales.');
        return false;
    }

    return true;
};

const send = async () => {
    if (checkValues()) {
        const url = 'http://127.0.0.1:8000/api/users';
        const options = {
            method: 'POST',
            headers: { 'content-type': 'application/json' },
            
            body: JSON.stringify({username,password,name,lastname})
        };

        try {
            const response = await fetch(url, options);
            const data = await response.json();
            console.log(data);
        } catch (error) {
            console.error(error);
        }
    }
}

return (
    <div>
        <table>
            <tr>
                <td>
                    <label>Username:</label>
                </td>
                <td>
                    <input value={username} type="text" onChange={(e) => setUsername(e.target.value)} />
                </td>
            </tr>
            <tr>
                <td>
                    <label>Password:</label>
                </td>
                <td><input value={password} type="password" onChange={(e) => setPassword(e.target.value)} /></td>
            </tr>
            <tr>
                <td>
                    <label>Confirm Password:</label>
                </td>
                <td><input value={confirm} type="password" onChange={(e) => setConfirm(e.target.value)} /></td>
            </tr>
            <tr>
                <td>
                    <label>Nombre:</label>
                </td>
                <td><input value={name} type="text" onChange={(e) => setName(e.target.value)} /></td>
            </tr>
            <tr>
                <td>
                    <label>Apellidos:</label>
                </td>
                <td><input value={lastname} type="text" onChange={(e) => setLastname(e.target.value)} /></td>
            </tr>
            <tr>
                <td></td>
                <td><button onClick={async () => await send()}>Register</button></td>
            </tr>
        </table>
    </div>
)
 }

  export default register;

And my react app are running with npx vite in: http://localhost:5173/

i tried so many things and nothing has worked maybe is easier only change the laravel version.

whatever i hope that someone know what is happening and can help me.I can send more information if is necesary

1
  • I am having the same issue after upgrading from Laravel 8. removed Fruitcake and added the following line: \Illuminate\Http\Middleware\HandleCors::class, in my Kernel.php file. Commented May 4 at 8:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.