Blog Post
Read this blog post by Sakib U. SiddiQuie.
Complete Guide to CORS & Axios: From Theory to Practical Implementation in Node.js, Laravel, React, and Angular
Thursday, September 25, 2025 at 04:00 AM
Complete Guide to CORS & Axios: From Theory to Practical Implementation in Node.js, Laravel, React, and Angular
Table of Contents
- Introduction
- Understanding CORS: What, Why, and How
- Same-Origin Policy (SOP)
- Cross-Origin Resource Sharing (CORS)
- How Browsers Enforce CORS
- Types of CORS Requests
- Simple Requests
- Preflighted Requests
- Important CORS Headers Explained
- Handling Credentials in CORS
- How to Enable and Configure CORS on Backend
- Node.js with Express
- PHP Laravel
- Axios: A Powerful HTTP Client
- Axios vs Fetch
- Installing Axios
- Using Axios in Frontend Frameworks
- React Example
- Angular Example
- Advanced Axios Usage
- Global Configuration
- Interceptors
- Error Handling
- Integrating Axios with CORS
- Common CORS and Axios Issues & How to Debug
- Best Practices & Tips
- CORS & Axios Cheatsheet
- Summary
Introduction
In modern web development, building applications with a separation between frontend and backend is commonplace. Frontend apps often need to interact with backend APIs hosted on different domains, ports, or protocols — triggering browser Cross-Origin Resource Sharing (CORS) policies.
Additionally, making HTTP requests in frontend apps is crucial — and Axios is one of the most popular libraries that simplifies these requests.
This guide aims to cover everything you need to understand and implement CORS handling and use Axios effectively in your projects, with practical examples in Node.js, Laravel, React, and Angular.
Understanding CORS: What, Why, and How
Same-Origin Policy (SOP)
- Browsers enforce Same-Origin Policy to restrict how scripts loaded from one origin can interact with resources from another origin.
- An "origin" is defined as the combination of protocol + domain + port.
- Example:
- http://example.com:3000 ≠ http://example.com:4000 (different port → different origin)
- http://example.com ≠ https://example.com (different protocol → different origin)
Cross-Origin Resource Sharing (CORS)
- CORS is a mechanism that allows servers to specify which origins are permitted to access their resources.
- It relaxes the SOP by explicitly whitelisting origins and HTTP methods via HTTP headers.
How Browsers Enforce CORS
- Browser sends an HTTP request with an Origin header indicating the source of the request.
- Server responds with specific CORS headers to allow or deny the request.
- Browser examines these headers:
- If headers permit, the browser allows the frontend script to read the response.
- Otherwise, the response is blocked by the browser.
Types of CORS Requests
Simple Requests
- Use safe HTTP methods: GET, POST, HEAD
- Only allow a limited set of headers (e.g., Accept, Content-Type with certain media types)
- Sent directly without preflight.
Preflighted Requests
- Include requests with:
- Methods other than GET, POST, HEAD (e.g., PUT, DELETE)
- Custom headers (like Authorization)
- Content-Type other than simple types (like application/json)
- Browser sends an OPTIONS request before the actual request to verify permission.
- Server responds with allowed methods and headers.
- If allowed, browser proceeds with actual request.
Important CORS Headers Explained
Header Description Access-Control-Allow-Origin Specifies the allowed origin(s). Can be a specific origin or * for all origins. Access-Control-Allow-Methods Lists allowed HTTP methods (used in preflight response). Access-Control-Allow-Headers Lists allowed headers client can send (preflight). Access-Control-Allow-Credentials Whether cookies or auth data can be sent (true or omitted). Access-Control-Expose-Headers Headers accessible to frontend JS (by default, only simple headers accessible). Access-Control-Max-Age Caches preflight results duration in seconds.
Handling Credentials in CORS
- Cookies, HTTP Auth, client-side SSL certificates are not sent by default on cross-origin requests.
- To enable:
- Client: Set withCredentials: true (Axios/fetch)
- Server: Set header Access-Control-Allow-Credentials: true
- Important:
- Cannot use * wildcard for Access-Control-Allow-Origin when Allow-Credentials is true.
- Must specify explicit origin.
How to Enable and Configure CORS on Backend
Node.js with Express
Detecting language...
Handling Preflight:
Detecting language...
PHP Laravel
- Laravel 8+ ships with CORS middleware pre-installed (HandleCors).
- Configure config/cors.php:
Detecting language...
- Ensure middleware is enabled in app/Http/Kernel.php under $middlewareGroups.
Axios: A Powerful HTTP Client
Axios vs Fetch
Feature Axios Fetch Syntax Simple and concise More verbose JSON parsing Automatic Manual with .json() Request & response interceptors Supported Not supported natively Request cancellation Supported Supported via AbortController Error handling Throws for HTTP errors Doesn't throw for HTTP errors Progress tracking Supported Not directly supported Works in Node.js Yes No
Installing Axios
Detecting language...
Using Axios in Frontend Frameworks
React Example
Detecting language...
Angular Example
Detecting language...
Detecting language...
Advanced Axios Usage
Global Configuration
Set common defaults for all Axios requests:
Detecting language...
Interceptors
Intercept requests or responses to modify or handle globally:
Detecting language...
Error Handling
Axios throws on HTTP errors (status outside 2xx). Use .catch() or try/catch with async/await.
Integrating Axios with CORS
- To send cookies or HTTP auth credentials on cross-origin requests:
Detecting language...
- Backend must have:
- Access-Control-Allow-Origin with explicit origin (not *)
- Access-Control-Allow-Credentials: true
Common CORS and Axios Issues & How to Debug
Issue Cause Fix CORS error in browser console Missing or incorrect CORS headers on backend Add correct CORS headers and handle preflight OPTIONS Access-Control-Allow-Origin is * but credentials fail Credentials not allowed with wildcard origin Specify exact origin, enable credentials on backend Preflight request fails Backend doesn’t handle OPTIONS request Add handler for OPTIONS preflight (Express app.options) Cookies not sent in request Missing withCredentials: true on client Add withCredentials: true in Axios/fetch Authorization headers missing Backend not allowing Authorization header Add Authorization to Access-Control-Allow-Headers
Best Practices & Tips
- Use specific origins, avoid * when cookies or auth are involved
- Centralize Axios config for maintainability
- Use interceptors for auth tokens or error handling
- Always test with browser DevTools (Network tab) for CORS headers and errors
- Use Postman or curl to test backend APIs — they bypass CORS restrictions
- Cache preflight responses via Access-Control-Max-Age for performance
CORS & Axios Cheatsheet
Task Backend (Node.js) Backend (Laravel) Frontend (Axios) Enable CORS app.use(cors({ origin: 'http://localhost:3000', credentials: true })) Set allowed_origins and supports_credentials in config/cors.php Use { withCredentials: true } in Axios requests Handle Preflight OPTIONS app.options('*', cors()) Middleware auto-handles OPTIONS No special config needed Allow credentials credentials: true and specific origin supports_credentials => true and specific origin withCredentials: true Set allowed headers allowedHeaders: ['Content-Type', 'Authorization'] allowed_headers config Set custom headers in Axios with headers option Global Axios config N/A N/A axios.defaults.baseURL and axios.defaults.withCredentials Add Auth token automatically N/A N/A Use axios.interceptors.request
Summary
- CORS is crucial for cross-origin security and enabling frontend-backend communication.
- Backend must send appropriate CORS headers, especially when handling credentials.
- Axios simplifies HTTP requests with powerful features like interceptors and automatic JSON handling.
- Always match frontend and backend origins exactly for CORS to work properly.
- Use withCredentials: true when cookies or authentication are involved.
- Debug CORS issues with browser DevTools and backend logs.
- Organize your code with global Axios configurations and interceptors for cleaner and scalable apps.
- Mastering SQL for Superset
- 🧠 All the APIs You Should Know (Part 3: Recommendations, Cheatsheets & Real-World Tips)
- 💻 All the APIs You Should Know (Part 2: Real Code Examples in Node.js + React)#web-development#react.js#fullstack#api
- CSS Layout, Display & Positioning — Developer Notes with Examples#web-development#frontend#ui#css
- 🔥 All The APIs You Should Know as a Developer (Part 1: Theory, Use Cases & Why They Exist)
- Complete Guide to CORS & Axios: From Theory to Practical Implementation in Node.js, Laravel, React, and Angular#laravel#node.js#angular#react.js#fullstack#api#next.js
- 🚀 All the API Types You Should Know (With Code Examples)#node.js#API Design#Backend Engineering#Web Development#react.js#System Architecture

