Bird
Raised Fist0
Expressframework~20 mins

cors middleware setup in Express - Practice Problems & Coding Challenges

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!
component_behavior
intermediate
2:00remaining
What is the output when CORS middleware allows only example.com?

Consider this Express server setup using CORS middleware:

import express from 'express';
import cors from 'cors';

const app = express();

app.use(cors({ origin: 'https://example.com' }));

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(3000);

What happens if a browser from https://notallowed.com tries to fetch data from this server?

AThe server responds normally and the browser accepts the response.
BThe browser blocks the response due to CORS policy.
CThe server returns a 404 error.
DThe server crashes with an error.
Attempts:
2 left
💡 Hint

Think about what CORS does when the origin is not in the allowed list.

📝 Syntax
intermediate
2:00remaining
Which option correctly sets up CORS to allow all origins?

Which of the following code snippets correctly configures the Express CORS middleware to allow requests from any origin?

Aapp.use(cors());
Bapp.use(cors({ origin: null }));
Capp.use(cors({ origin: '*' }));
Dapp.use(cors({ origin: false }));
Attempts:
2 left
💡 Hint

Check the default behavior of the CORS middleware when no options are passed.

🔧 Debug
advanced
2:00remaining
Why does this CORS setup cause a runtime error?

Examine this Express server code snippet:

import express from 'express';
import cors from 'cors';

const app = express();

app.use(cors({ origin: '*', credentials: true }));

app.get('/', (req, res) => {
  res.send('Hello');
});

app.listen(3000);

When running this code, the server crashes with an error related to the CORS origin option. Why?

AThe CORS middleware does not support HTTPS URLs.
BThe app.listen call is missing a callback function.
CThe origin array must be wrapped inside another object.
DThe origin '*' cannot be used when credentials: true.
Attempts:
2 left
💡 Hint

Check the compatibility between origin and credentials options.

🧠 Conceptual
advanced
2:00remaining
What is the purpose of the 'optionsSuccessStatus' option in CORS middleware?

In the CORS middleware configuration, what does setting optionsSuccessStatus do?

AIt sets the HTTP status code sent for successful OPTIONS preflight requests.
BIt specifies the allowed HTTP methods for CORS.
CIt disables CORS for OPTIONS requests.
DIt defines the maximum age for caching CORS headers.
Attempts:
2 left
💡 Hint

Think about how browsers check permissions before sending actual requests.

state_output
expert
2:00remaining
What is the value of the 'Access-Control-Allow-Origin' header for this request?

Given this Express server code:

import express from 'express';
import cors from 'cors';

const app = express();

const whitelist = ['https://allowed.com', 'https://trusted.com'];

app.use(cors({
  origin: (origin, callback) => {
    if (!origin || whitelist.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
}));

app.get('/', (req, res) => {
  res.send('Welcome');
});

app.listen(3000);

If a request comes from https://allowed.com, what will be the value of the Access-Control-Allow-Origin header in the response?

Aundefined (header not set)
B'*'
C'https://allowed.com'
D'https://trusted.com'
Attempts:
2 left
💡 Hint

Look at how the origin callback controls allowed origins.

Practice

(1/5)
1. What is the main purpose of using the cors middleware in an Express app?
easy
A. To allow or restrict which websites can access your server resources
B. To handle database connections securely
C. To serve static files like images and CSS
D. To log HTTP requests for debugging

Solution

  1. 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.
  2. Step 2: Identify the role of the middleware

    The cors middleware in Express is used to set these access rules to allow or restrict cross-origin requests.
  3. Final Answer:

    To allow or restrict which websites can access your server resources -> Option A
  4. Quick Check:

    CORS controls access permissions = B [OK]
Hint: Remember CORS controls cross-site access permissions [OK]
Common Mistakes:
  • Confusing CORS with logging or static file serving
  • Thinking CORS manages database security
  • Assuming CORS is for request logging
2. Which of the following is the correct way to enable CORS for all routes in an Express app?
easy
A. app.use(cors());
B. app.use(cors);
C. app.cors();
D. app.enable(cors);

Solution

  1. Step 1: Recall the syntax for middleware usage

    In Express, middleware functions are passed as functions, so you must call cors() to get the middleware function.
  2. Step 2: Identify the correct usage

    app.use(cors()); correctly calls the cors function and applies it to all routes.
  3. Final Answer:

    app.use(cors()); -> Option A
  4. Quick Check:

    Middleware needs function call = A [OK]
Hint: Always call middleware functions with parentheses [OK]
Common Mistakes:
  • Forgetting parentheses after cors
  • Using app.cors() which is not a method
  • Trying app.enable(cors) which is invalid
3. Given this Express code snippet, what will be the CORS behavior?
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);
medium
A. Only POST requests from any origin are allowed
B. All origins are allowed to access /data
C. Only requests from https://example.com will be allowed by browsers
D. No origins are allowed, CORS is disabled

Solution

  1. Step 1: Analyze the CORS options

    The cors middleware is configured with { origin: 'https://example.com' }, which restricts access to that origin only.
  2. Step 2: Understand the effect on requests

    Browsers will allow cross-origin requests only from https://example.com. Requests from other origins will be blocked by the browser.
  3. Final Answer:

    Only requests from https://example.com will be allowed by browsers -> Option C
  4. Quick Check:

    Origin option restricts access = D [OK]
Hint: Check the origin option to know allowed sites [OK]
Common Mistakes:
  • Assuming all origins are allowed by default
  • Thinking CORS disables all requests without origin option
  • Confusing HTTP methods with origin restrictions
4. Identify the error in this Express CORS setup:
import express from 'express';
import cors from 'cors';
const app = express();

app.use(cors);

app.get('/', (req, res) => res.send('Hi'));

app.listen(3000);
medium
A. app.listen should be called before app.use
B. cors should be imported from 'express-cors' package
C. No error, this code works fine
D. Missing parentheses after cors in app.use

Solution

  1. Step 1: Check how cors middleware is applied

    The code uses app.use(cors); but cors is a function that must be called to return middleware.
  2. Step 2: Correct usage requires parentheses

    The correct syntax is app.use(cors()); to apply the middleware properly.
  3. Final Answer:

    Missing parentheses after cors in app.use -> Option D
  4. Quick Check:

    Middleware must be called = C [OK]
Hint: Middleware needs parentheses to run correctly [OK]
Common Mistakes:
  • Forgetting to call cors() as a function
  • Importing cors from wrong package
  • Thinking app.listen order affects middleware
5. You want to allow CORS only for GET and POST requests from https://myapp.com but block others. Which setup correctly achieves this?
hard
A. app.use(cors({ origin: '*', methods: ['GET', 'POST'] }));
B. app.use(cors({ origin: 'https://myapp.com', methods: ['GET', 'POST'] }));
C. app.use(cors({ origin: 'https://myapp.com' })); // methods ignored
D. app.use(cors({ methods: ['GET', 'POST'] }));

Solution

  1. Step 1: Understand the origin restriction

    To allow only https://myapp.com, set origin: 'https://myapp.com'.
  2. Step 2: Restrict HTTP methods

    Use methods: ['GET', 'POST'] to allow only those request types.
  3. 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.
  4. Final Answer:

    app.use(cors({ origin: 'https://myapp.com', methods: ['GET', 'POST'] })); -> Option B
  5. Quick Check:

    Origin + methods options restrict access = A [OK]
Hint: Set both origin and methods to restrict CORS properly [OK]
Common Mistakes:
  • Using '*' origin allows all sites
  • Ignoring methods option when restricting HTTP verbs
  • Assuming methods alone restrict origin