Complete the code to handle OPTIONS preflight requests in Express.
app.[1]('/api/data', (req, res) => { res.sendStatus(204); });
The OPTIONS method is used to handle preflight requests in Express.
Complete the code to set the Access-Control-Allow-Origin header for CORS.
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', [1]);
next();
});Setting Access-Control-Allow-Origin to '*' allows all origins to access the resource.
Fix the error in the code to allow specific methods in preflight response.
app.options('/api/data', (req, res) => { res.setHeader('Access-Control-Allow-Methods', [1]); res.sendStatus(204); });
The header value must be a comma-separated list of allowed HTTP methods in uppercase.
Fill both blanks to allow credentials and specific headers in CORS preflight.
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Credentials', [1]);
res.setHeader('Access-Control-Allow-Headers', [2]);
next();
});Allowing credentials requires 'true' as a string, and headers must be a comma-separated string.
Fill all three blanks to complete a middleware that handles CORS preflight requests properly.
app.use((req, res, next) => {
if (req.method === [1]) {
res.setHeader('Access-Control-Allow-Origin', [2]);
res.setHeader('Access-Control-Allow-Methods', [3]);
res.sendStatus(204);
} else {
next();
}
});The middleware checks if the method is OPTIONS, then sets headers to allow all origins and specific methods.