A. Calling cors() twice causes conflict and overrides settings
B. The methods option is invalid in cors middleware
C. The origin value should be an array, not a string
D. Missing next() call in middleware
Solution
Step 1: Check middleware usage order
Calling cors() twice means the second call overrides the first, ignoring origin restrictions.
Step 2: Confirm methods option is valid
The methods option is valid to restrict HTTP methods, so no error there.
Final Answer:
Calling cors() twice causes conflict and overrides settings -> Option A
Quick Check:
Multiple cors calls override previous config [OK]
Hint: Only call cors once with all options [OK]
Common Mistakes:
Calling cors middleware multiple times
Thinking origin must be array always
Ignoring middleware order effects
5. You want to allow requests only from origins that end with '.trusted.com' dynamically in Express. Which cors configuration correctly implements this?
hard
A. app.use(cors({ origin: ['*.trusted.com'] }));
B. app.use(cors({ origin: (origin, callback) => { if (origin.includes('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } }));
C. app.use(cors({ origin: '/^https:\/\/.*\.trusted\.com$/' }));
D. app.use(cors({ origin: (origin, callback) => { if (origin.endsWith('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } }));
Solution
Step 1: Understand dynamic origin checking
To allow origins ending with '.trusted.com', a function can check the origin string dynamically.
Step 2: Evaluate each option's approach
app.use(cors({ origin: (origin, callback) => { if (origin.endsWith('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } })); uses a function with endsWith to precisely match the domain ending, which is correct. app.use(cors({ origin: ['*.trusted.com'] })); uses wildcard string which is not supported. app.use(cors({ origin: '/^https:\/\/.*\.trusted\.com$/' })); uses regex but cors does not accept regex directly. app.use(cors({ origin: (origin, callback) => { if (origin.includes('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } })); uses includes which may allow unwanted matches.
Final Answer:
app.use(cors({ origin: (origin, callback) => { if (origin.endsWith('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } })); -> Option D
Quick Check:
Use function with endsWith for dynamic origin [OK]
Hint: Use function with endsWith() to allow domain patterns [OK]