The Problem
You're getting this error in your browser console:
Access to fetch at 'http://localhost:8000/api/users' from origin
'http://localhost:3000' has been blocked by CORS policy
Why This Happens
Browsers block requests from one origin (localhost:3000) to another (localhost:8000) for security. This is called the Same-Origin Policy.
Solution: Configure Laravel CORS
Step 1: Update config/cors.php
<?php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => [
'http://localhost:3000',
'http://localhost:5173', // Vite
env('FRONTEND_URL', 'https://yourapp.com'),
],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
Step 2: Configure React/Axios
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:8000/api',
withCredentials: true, // Important for cookies!
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
export default api;
Step 3: For Laravel Sanctum (SPA Auth)
// First, get CSRF cookie
await axios.get('http://localhost:8000/sanctum/csrf-cookie', {
withCredentials: true
});
// Then login
await api.post('/login', { email, password });
Common Mistakes
- Forgetting
withCredentials: true - Using
'*'for allowed_origins with credentials - Not including
sanctum/csrf-cookiein paths
Production Checklist
- Use specific origins, never
'*' - Use environment variables for URLs
- Test both HTTP and HTTPS
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!