Beginner LevelExpress JS
How does res.format() implement HTTP Content Negotiation based on client Accept headers?
❓ Interview Prompt: Explain HTTP Content Negotiation, res.format(), inspecting client Accept headers, and returning JSON vs HTML vs Plaintext.
'res.format()' performs HTTP Content Negotiation by inspecting the client's incoming 'Accept' header and executing matching format callbacks ('application/json', 'text/html', 'text/plain'). Returns 406 Not Acceptable if no match exists.
Code Implementation Example
javascript
import express from 'express';
const app = express();
app.get('/api/data', (req, res) => {
const data = { message: 'Hello World' };
// Content negotiation based on client Accept header!
res.format({
'application/json': () => res.json(data),
'text/html': () => res.send(`<p>${data.message}</p>`),
'text/plain': () => res.send(data.message),
default: () => res.status(406).send('Not Acceptable')
});
});💡Performing HTTP Content Negotiation using res.format.
🎯 Interview Key Takeaway
Use res.format() to execute different response formatting callbacks based on the client Accept header.
#res.format#Content Negotiation#Beginner
Back to all Express JS Questions→