Choose the correct explanation of CORS and its purpose in web development.
Think about how browsers handle requests from one website to another domain.
CORS stands for Cross-Origin Resource Sharing. It is a security feature that allows controlled access to resources on a web server from a different domain than the one serving the web page. This prevents malicious sites from reading sensitive data from another domain.
Given the following Express server code with CORS configured, what will the browser receive when a request comes from http://example.com?
import express from 'express'; import cors from 'cors'; const app = express(); app.use(cors({ origin: 'http://example.com' })); app.get('/', (req, res) => { res.json({ message: 'Hello World' }); }); app.listen(3000);
Check how the cors middleware is configured and what it does.
The cors middleware adds the appropriate headers to allow requests from http://example.com. The server responds with the JSON and the browser accepts it because the origin matches.
Choose the code snippet that correctly allows CORS requests from http://site1.com and http://site2.com only.
The cors package supports arrays for the origin option.
Option B is correct because the cors middleware supports an array of strings directly for the origin option to allow multiple specific origins only. Option B treats the comma-separated value as a single origin. Option B uses Error which propagates an error to the next middleware instead of cleanly denying. Option B uses invalid format.
Examine the code below. Why does the server crash when starting?
import express from 'express'; import cors from 'cors'; const app = express(); app.use(cors({ origin: true })); app.listen(3000);
Check the documentation for the cors package about the origin option.
Setting origin to true in the cors middleware allows requests from any origin. This is valid and does not cause a runtime error. The server crash must be caused by something else, but none of the other options match the code given.
Given this Express server code and a request from http://evil.com, what will be the value of the Access-Control-Allow-Origin header in the response?
import express from 'express'; import cors from 'cors'; const allowedOrigins = ['http://good.com', 'http://friend.com']; const app = express(); app.use(cors({ origin: (origin, callback) => { if (!origin) return callback(null, true); if (allowedOrigins.includes(origin)) { callback(null, origin); } else { callback(null, false); } } })); app.get('/', (req, res) => { res.send('Hello'); }); app.listen(3000);
Consider what happens when the origin is not in the allowed list and how the callback is called.
If the origin is not in the allowedOrigins list, the callback is called with false, which means no CORS headers are set. Therefore, the Access-Control-Allow-Origin header is not included in the response.