DEV Community

Cover image for Fix Common CORS Errors in APIs and Frontend Apps
Rafli Zocky
Rafli Zocky

Posted on Originally published at Medium

Fix Common CORS Errors in APIs and Frontend Apps

I've spent many hours solving this…

Cross-Origin Resource Sharing (CORS) errors are a regular part of web development. More info: MDN CORS Guide.

Issue 1: No Access-Control-Allow-Origin Header

Access to XMLHttpRequest blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Enter fullscreen mode Exit fullscreen mode

The frontend is calling a backend endpoint without proper CORS configuration. Fix:

'allowed_origins' => [
    'http://localhost:3000',
    'http://localhost:5173',
],
Enter fullscreen mode Exit fullscreen mode

For Laravel 11+:

php artisan config:publish cors
Enter fullscreen mode Exit fullscreen mode

Then edit config/cors.php. Most frameworks have built-in CORS support — look for config files or middleware.

Issue 2: Credentials with Wildcard Origins

The 'Access-Control-Allow-Origin' header value must not be '*' when the
request's credentials mode is 'include'.
Enter fullscreen mode Exit fullscreen mode

Using withCredentials: true with allowed_origins: ['*'] is not allowed by browsers. Specify exact trusted origins:

const api = axios.create({
  baseURL: "http://127.0.0.1:8000",
  withCredentials: true,
});
Enter fullscreen mode Exit fullscreen mode
'allowed_origins' => ['https://yourdomain.com'], // NOT ['*']
'supports_credentials' => true,
Enter fullscreen mode Exit fullscreen mode

Issue 3: Wrong API Endpoint

Calling /login instead of /api/login — accidentally hitting the web route instead of the API route.

# Check your routes first
php artisan route:list | grep login
Enter fullscreen mode Exit fullscreen mode
// Fix the endpoint
const response = await api.post('/api/login', data); // Add /api prefix
Enter fullscreen mode Exit fullscreen mode

Issue 4: Config Changes Not Applied

# Clear all cache in Laravel
php artisan optimize:clear

# Restart dev server
ctrl + c
npm run dev
Enter fullscreen mode Exit fullscreen mode

Most problems stem from configuration mismatches rather than complex setup issues.


Need help building your app?
I'm available for freelance web & Android development — raflizocky.netlify.app

☕ Support my writing: paypal.me/raflizocky · saweria.co/raflizocky

Top comments (0)