CORS is a security feature that lets servers specify who can access their resources from different origins. It prevents unauthorized cross-site requests.
If the API does not send CORS headers, browsers block the response to protect the user from unauthorized cross-origin requests.
const express = require('express'); const app = express(); // Which code below enables CORS for all origins?
Setting the header 'Access-Control-Allow-Origin' to '*' allows any origin to access the API. Option A does this correctly.
Middleware like cors() must be used before routes to set headers properly. If routes run first, CORS headers won't be set.
The code handles OPTIONS requests by sending status 204 with the correct CORS headers allowing the origin, methods, and headers.
