Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

satriamuda's avatar

has been blocked by CORS policy:

akses api to laravel :

Access to XMLHttpRequest at 'http://localhost:8000/login' from origin 'http://localhost:3000' 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.

import React, { useState } from 'react' import App from './../../layouts/App'; import axios from 'axios'

axios.defaults.withcredentials = true

export default function Login() {

const [email,setEmail]= useState('');
const [password,setPassword]= useState('');

let credentials = {email,password}


const submitHandler = async (e) =>{
    e.preventDefault()

    await axios.get('http://localhost:8000/sanctum/csrf-cookie')
    await axios.post('http://localhost:8000/login', credentials)

    let { data } = await axios.get('http://localhost:8000/api/me')

    console.log(data.data);
}

return (
    <App title="Login">
<div className="row">

    <div className="col-md-4">

        <div className="card">
            <div className="card-header">Login</div>
            <div className="card-body">

                <form onSubmit={submitHandler}>

                <div className="mb-3">
                    <label htmlFor="email" className="form-label">Email</label>
                    <input type="email" value={email} onChange={(e)=>setEmail(e.target.value)} name="email" id="email" className="form-control" />
                </div>

                <div className="mb-3">
                    <label htmlFor="password" className="form-label">Password</label>
                    <input type="password" value={password} onChange={(e)=>setPassword(e.target.value)} name="password" id="password" className="form-control" />
                </div>
                <button type="submit" className="btn btn-primary">Login</button>

                </form>
            </div>
        </div>
    </div>
</div>
    </App>
)

}

LARAVEL CONFIG->CORS: 'paths' => [ 'api/*', 'sanctum/csrf-cookie', 'login', 'register', 'logout' ],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

];

0 likes
1 reply
Tray2's avatar
Tray2
Best Answer
Level 73

It's always tricky with localhost and ajax.

Not knowing what OS you are using but I suggest you setup a proper webserver.

If you are on a Mac I recommend Valet or Sail. If you are on windows I suggest you use homestead or set up your own lamp/lemp stack.

https://www.howtoforge.com/tutorial/install-laravel-on-ubuntu-for-apache/

https://www.howtoforge.com/dockerizing-laravel-with-nginx-mysql-and-docker-compose/

https://www.howtoforge.com/tutorial/ubuntu-laravel-php-nginx/

Please or to participate in this conversation.