CORS middleware helps your server allow or block requests from other websites. It keeps your app safe and controls who can use your data.
cors middleware setup in Express
Start learning this pattern below
Jump into concepts and practice - no test required
import cors from 'cors'; import express from 'express'; const app = express(); // Use default CORS settings app.use(cors()); // Or customize CORS options const corsOptions = { origin: 'https://example.com', methods: ['GET', 'POST'], allowedHeaders: ['Content-Type', 'Authorization'] }; app.use(cors(corsOptions));
Import the cors package and use it as middleware in your Express app.
You can use default settings or pass options to control who can access your server.
app.use(cors());
app.use(cors({ origin: 'https://mywebsite.com' }));app.use(cors({ methods: ['GET', 'POST'] }));app.use(cors({ origin: ['https://site1.com', 'https://site2.com'] }));This Express server uses CORS middleware to allow only requests from https://example.com. When you visit http://localhost:3000, it responds with a greeting message.
import express from 'express'; import cors from 'cors'; const app = express(); // Allow only https://example.com to access app.use(cors({ origin: 'https://example.com' })); app.get('/', (req, res) => { res.send('Hello from CORS-enabled server!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Browsers enforce CORS, so this middleware mainly affects browser requests.
Always specify origins carefully to avoid security risks.
You can also configure other options like allowed headers and credentials.
CORS middleware controls which websites can access your Express server.
Use app.use(cors()) for open access or pass options to restrict access.
Proper CORS setup helps keep your app safe and avoids browser errors.
Practice
cors middleware in an Express app?Solution
Step 1: Understand what CORS controls
CORS stands for Cross-Origin Resource Sharing and it controls which external websites can access your server's resources.Step 2: Identify the role of the middleware
Thecorsmiddleware in Express is used to set these access rules to allow or restrict cross-origin requests.Final Answer:
To allow or restrict which websites can access your server resources -> Option AQuick Check:
CORS controls access permissions = B [OK]
- Confusing CORS with logging or static file serving
- Thinking CORS manages database security
- Assuming CORS is for request logging
Solution
Step 1: Recall the syntax for middleware usage
In Express, middleware functions are passed as functions, so you must callcors()to get the middleware function.Step 2: Identify the correct usage
app.use(cors());correctly calls thecorsfunction and applies it to all routes.Final Answer:
app.use(cors()); -> Option AQuick Check:
Middleware needs function call = A [OK]
- Forgetting parentheses after cors
- Using app.cors() which is not a method
- Trying app.enable(cors) which is invalid
import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors({ origin: 'https://example.com' }));
app.get('/data', (req, res) => {
res.json({ message: 'Hello' });
});
app.listen(3000);Solution
Step 1: Analyze the CORS options
Thecorsmiddleware is configured with{ origin: 'https://example.com' }, which restricts access to that origin only.Step 2: Understand the effect on requests
Browsers will allow cross-origin requests only fromhttps://example.com. Requests from other origins will be blocked by the browser.Final Answer:
Only requests from https://example.com will be allowed by browsers -> Option CQuick Check:
Origin option restricts access = D [OK]
- Assuming all origins are allowed by default
- Thinking CORS disables all requests without origin option
- Confusing HTTP methods with origin restrictions
import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors);
app.get('/', (req, res) => res.send('Hi'));
app.listen(3000);Solution
Step 1: Check how cors middleware is applied
The code usesapp.use(cors);butcorsis a function that must be called to return middleware.Step 2: Correct usage requires parentheses
The correct syntax isapp.use(cors());to apply the middleware properly.Final Answer:
Missing parentheses after cors in app.use -> Option DQuick Check:
Middleware must be called = C [OK]
- Forgetting to call cors() as a function
- Importing cors from wrong package
- Thinking app.listen order affects middleware
https://myapp.com but block others. Which setup correctly achieves this?Solution
Step 1: Understand the origin restriction
To allow onlyhttps://myapp.com, setorigin: 'https://myapp.com'.Step 2: Restrict HTTP methods
Usemethods: ['GET', 'POST']to allow only those request types.Step 3: Combine both options correctly
app.use(cors({ origin: 'https://myapp.com', methods: ['GET', 'POST'] })); correctly sets both origin and methods to restrict access as required.Final Answer:
app.use(cors({ origin: 'https://myapp.com', methods: ['GET', 'POST'] })); -> Option BQuick Check:
Origin + methods options restrict access = A [OK]
- Using '*' origin allows all sites
- Ignoring methods option when restricting HTTP verbs
- Assuming methods alone restrict origin
