Bird
Raised Fist0
Expressframework~20 mins

Why CORS matters for APIs in Express - Challenge Your Understanding

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
CORS Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the main purpose of CORS in APIs?
Why do APIs implement CORS (Cross-Origin Resource Sharing)?
ATo allow web pages from different origins to access API resources securely
BTo speed up API response times by caching data
CTo encrypt API data during transmission
DTo restrict API access only to mobile devices
Attempts:
2 left
💡 Hint
Think about how browsers control access to resources from different websites.
component_behavior
intermediate
2:00remaining
What happens if an API does not set CORS headers?
Consider a browser-based app trying to fetch data from an API that does not send CORS headers. What will happen?
AThe API response is cached indefinitely
BThe browser blocks the response and shows a CORS error
CThe API returns a 404 Not Found error
DThe browser automatically adds CORS headers to the request
Attempts:
2 left
💡 Hint
Browsers enforce CORS to protect users from malicious sites.
📝 Syntax
advanced
2:00remaining
Which Express code snippet correctly enables CORS for all origins?
Choose the Express.js code that properly enables CORS for any website to access the API.
Express
const express = require('express');
const app = express();
// Which code below enables CORS for all origins?
Aapp.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); next(); });
Bapp.use(cors({ origin: 'http://example.com' }));
Capp.use(cors({ origin: '*' }));
Dapp.use((req, res) => { res.header('Access-Control-Allow-Origin', 'none'); next(); });
Attempts:
2 left
💡 Hint
Look for the code that sets the header to allow all origins.
🔧 Debug
advanced
2:00remaining
Why does this Express CORS setup cause errors?
Given this Express code, why might CORS errors still occur? const cors = require('cors'); app.use((req, res) => { res.send('Hello'); }); app.use(cors());
ABecause the app does not listen on a port
BBecause the response is sent before CORS headers are set
CBecause the cors package is not installed
DBecause cors() middleware is not called before routes
Attempts:
2 left
💡 Hint
Middleware order matters in Express.
state_output
expert
2:00remaining
What is the output of this Express CORS preflight handling code?
What response headers will the server send when a browser sends an OPTIONS preflight request to this Express API? const express = require('express'); const app = express(); app.use((req, res, next) => { if (req.method === 'OPTIONS') { res.setHeader('Access-Control-Allow-Origin', 'https://example.com'); res.setHeader('Access-Control-Allow-Methods', 'GET,POST'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); return res.status(204).end(); } next(); }); app.get('/', (req, res) => res.send('OK')); // Assume a browser sends OPTIONS request from https://example.com
AStatus 404 Not Found with no headers
BStatus 200 with body 'OK' and no CORS headers
CStatus 204 with headers: Access-Control-Allow-Origin: https://example.com, Access-Control-Allow-Methods: GET,POST, Access-Control-Allow-Headers: Content-Type
DStatus 500 Internal Server Error due to missing next() call
Attempts:
2 left
💡 Hint
Preflight requests use OPTIONS method and expect specific CORS headers.

Practice

(1/5)
1. What is the main reason CORS is important for APIs in Express?
easy
A. It encrypts the data sent by the API.
B. It speeds up the API response time.
C. It automatically logs all API requests.
D. It controls which websites can access your API to protect it.

Solution

  1. Step 1: Understand CORS purpose

    CORS stands for Cross-Origin Resource Sharing and it controls which websites can call your API.
  2. Step 2: Identify protection role

    By controlling access, CORS protects your API from unwanted or malicious websites.
  3. Final Answer:

    It controls which websites can access your API to protect it. -> Option D
  4. Quick Check:

    CORS controls access = D [OK]
Hint: Remember: CORS controls access, not speed or encryption [OK]
Common Mistakes:
  • Thinking CORS speeds up API
  • Confusing CORS with logging
  • Believing CORS encrypts data
2. Which Express middleware is commonly used to enable CORS?
easy
A. cors
B. express-session
C. body-parser
D. morgan

Solution

  1. Step 1: Recall Express middleware for CORS

    The npm package named 'cors' is the standard middleware to enable CORS in Express.
  2. Step 2: Identify other middleware roles

    express-session manages sessions, body-parser parses request bodies, morgan logs requests, none handle CORS.
  3. Final Answer:

    cors -> Option A
  4. Quick Check:

    Enable CORS with 'cors' middleware = B [OK]
Hint: Use 'cors' package to enable CORS in Express apps [OK]
Common Mistakes:
  • Choosing body-parser for CORS
  • Confusing logging middleware with CORS
  • Using session middleware for CORS
3. What will happen if an API does NOT set CORS headers and a browser tries to call it from another website?
medium
A. The browser will block the request due to CORS policy.
B. The API will respond faster without CORS headers.
C. The API will automatically allow all websites.
D. The browser will ignore CORS and allow the request.

Solution

  1. Step 1: Understand browser CORS enforcement

    Browsers enforce CORS by blocking cross-origin requests if the server does not send proper CORS headers.
  2. Step 2: Identify consequences of missing CORS headers

    Without CORS headers, the browser blocks the request; the API itself may respond but browser denies access.
  3. Final Answer:

    The browser will block the request due to CORS policy. -> Option A
  4. Quick Check:

    Missing CORS headers = browser blocks request = A [OK]
Hint: No CORS headers means browser blocks cross-site calls [OK]
Common Mistakes:
  • Thinking API blocks request instead of browser
  • Assuming API allows all without CORS
  • Believing browser ignores CORS
4. Consider this Express code snippet:
const express = require('express');
const app = express();

app.get('/data', (req, res) => {
  res.json({ message: 'Hello' });
});

app.listen(3000);
What is missing to allow cross-origin requests safely?
medium
A. Adding a body-parser middleware.
B. Changing app.get to app.post.
C. Adding CORS middleware to set proper headers.
D. Using HTTPS instead of HTTP.

Solution

  1. Step 1: Identify missing CORS headers

    The code does not include any middleware to set CORS headers, so cross-origin requests will be blocked by browsers.
  2. Step 2: Recognize correct fix

    Adding CORS middleware (like 'cors' package) will add headers to allow safe cross-origin requests.
  3. Final Answer:

    Adding CORS middleware to set proper headers. -> Option C
  4. Quick Check:

    Add CORS middleware to allow cross-origin = A [OK]
Hint: Add 'cors' middleware to fix cross-origin blocking [OK]
Common Mistakes:
  • Thinking HTTP method change fixes CORS
  • Confusing body parsing with CORS
  • Believing HTTPS alone solves CORS
5. You want your Express API to allow only requests from https://example.com but block others. Which CORS configuration achieves this?
hard
A. app.use(cors());
B. app.use(cors({ origin: 'https://example.com' }));
C. app.use(cors({ origin: '*' }));
D. app.use(cors({ methods: ['GET', 'POST'] }));

Solution

  1. Step 1: Understand origin option in CORS

    The 'origin' option in the cors middleware specifies which website origins are allowed to access the API.
  2. Step 2: Match requirement to configuration

    Setting origin to 'https://example.com' allows only that site; '*' allows all, no origin restricts, methods restrict HTTP verbs only.
  3. Final Answer:

    app.use(cors({ origin: 'https://example.com' })); -> Option B
  4. Quick Check:

    Restrict origin to example.com = C [OK]
Hint: Set origin to specific URL to restrict access [OK]
Common Mistakes:
  • Using '*' allows all origins, not restricted
  • Omitting origin allows all by default
  • Confusing methods with origin restriction