Challenge - 5 Problems
CORS Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
What is the main purpose of CORS in APIs?
Why do APIs implement CORS (Cross-Origin Resource Sharing)?
Attempts:
2 left
💡 Hint
Think about how browsers control access to resources from different websites.
✗ Incorrect
CORS is a security feature that lets servers specify who can access their resources from different origins. It prevents unauthorized cross-site requests.
❓ component_behavior
intermediate2: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?
Attempts:
2 left
💡 Hint
Browsers enforce CORS to protect users from malicious sites.
✗ Incorrect
If the API does not send CORS headers, browsers block the response to protect the user from unauthorized cross-origin requests.
📝 Syntax
advanced2: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?
Attempts:
2 left
💡 Hint
Look for the code that sets the header to allow all origins.
✗ Incorrect
Setting the header 'Access-Control-Allow-Origin' to '*' allows any origin to access the API. Option A does this correctly.
🔧 Debug
advanced2: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());
Attempts:
2 left
💡 Hint
Middleware order matters in Express.
✗ Incorrect
Middleware like cors() must be used before routes to set headers properly. If routes run first, CORS headers won't be set.
❓ state_output
expert2: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
Attempts:
2 left
💡 Hint
Preflight requests use OPTIONS method and expect specific CORS headers.
✗ Incorrect
The code handles OPTIONS requests by sending status 204 with the correct CORS headers allowing the origin, methods, and headers.