react login component
axios.defaults.withCredentials = true;
axios.defaults.baseURL = 'http://127.0.0.1:8000';
const handleSubmit = async (e) => {
e.preventDefault();
await axios.get('/sanctum/csrf-cookie')
.then(() => {
return axios.post('/api/login', formData);
})
.then((response) => {
console.log('Logged in successfully:', response.data);
// Maybe redirect or fetch user
})
.catch((error) => {
console.error('Login failed:', error.response?.data || error.message);
alert("Login failed");
});
};
cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['http://localhost:5173'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,localhost:5173,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
// Sanctum::currentRequestHost(),
))),
login function
$credentials = $request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
if(Auth::attempt($credentials)){
$request->session()->regenerate();
return response()->json(['message' => 'Login successful'], 200);
}
return response()->json(['message' => 'Invalid credentials'], 401);
}
env
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost