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?
Think about what CORS does when the origin is not in the allowed list.
The CORS middleware restricts access to only requests from 'https://example.com'. Requests from other origins like 'https://notallowed.com' will be blocked by the browser due to CORS policy.
Which of the following code snippets correctly configures the Express CORS middleware to allow requests from any origin?
Check the default behavior of the CORS middleware when no options are passed.
Calling cors() without options allows all origins by default (equivalent to {origin: true}). {origin: '*'} also allows all origins.
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?
Check the compatibility between origin and credentials options.
The CORS middleware throws an error when origin: '*' is used with credentials: true because credentials require specific allowed origins for security reasons.
In the CORS middleware configuration, what does setting optionsSuccessStatus do?
Think about how browsers check permissions before sending actual requests.
The optionsSuccessStatus option sets the status code returned for successful OPTIONS preflight requests, often set to 200 to support older browsers that do not handle 204 well.
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?
Look at how the origin callback controls allowed origins.
The callback allows origins in the whitelist. For 'https://allowed.com', the header is set exactly to that origin.