Given this Express server code configuring CORS origins, what will happen when a request comes from 'http://example.com'?
const express = require('express'); const cors = require('cors'); const app = express(); const allowedOrigins = ['http://example.com', 'http://localhost:3000']; app.use(cors({ origin: function(origin, callback) { if (!origin || allowedOrigins.includes(origin)) { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } } })); app.get('/', (req, res) => { res.send('Hello World'); }); app.listen(3000);
Check if 'http://example.com' is in the allowedOrigins array.
The origin 'http://example.com' is included in the allowedOrigins array, so the CORS middleware allows the request and the server responds normally.
Select the correct CORS middleware configuration to allow requests only from 'http://myapp.com'.
Check the type expected for the origin option in the CORS middleware.
The origin option accepts a string for a single allowed origin. Option C correctly sets it to 'http://myapp.com'. Option C returns a boolean but the function should call a callback. Option C allows all origins.
Analyze the code below. Why does it block all cross-origin requests?
const allowedOrigins = ['http://site1.com', 'http://site2.com']; app.use(cors({ origin: function(origin, callback) { if (allowedOrigins.indexOf(origin) >= 0) { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } } }));
Remember how JavaScript treats 0 in conditions.
The indexOf method returns 0 for the first element, which is falsy in JavaScript. The if condition fails for the first allowed origin, blocking it incorrectly. The condition should check for index >= 0.
Consider this code snippet. What is the final value of the 'allowedOrigins' variable?
let allowedOrigins = ['http://a.com', 'http://b.com']; allowedOrigins.push('http://c.com'); allowedOrigins = allowedOrigins.filter(origin => origin !== 'http://b.com');
Think about what filter does to the array.
The push adds 'http://c.com' to the array. The filter removes 'http://b.com', so the final array has 'http://a.com' and 'http://c.com'.
Why do developers configure allowed origins in Express applications using CORS middleware?
Think about what CORS controls in web browsers.
CORS configuration controls which external websites can access server resources, protecting against unauthorized cross-origin requests. It is a security feature, not related to performance or authentication.