Intermediate LevelExpress JS
How do you use req.accepts() to inspect client content capabilities?
❓ Interview Prompt: Explain req.accepts(), req.acceptsLanguages(), req.acceptsEncodings(), and evaluating client HTTP capability headers.
'req.accepts(types)' checks if the specified media types are acceptable based on the client's HTTP 'Accept' request header:
•
Returns the best matching type string (e.g. '"json"', '"html"') or 'false' if none match.
•
Companion methods: 'req.acceptsLanguages()' and 'req.acceptsEncodings()'.
Code Implementation Example
javascript
import express from 'express';
const app = express();
app.get('/api/resource', (req, res) => {
// Inspect client Accept header preference
const type = req.accepts(['json', 'html', 'xml']);
if (type === 'json') {
res.json({ type: 'json' });
} else if (type === 'html') {
res.send('<p>Type: HTML</p>');
} else {
res.status(406).send('Not Acceptable');
}
});💡Inspecting client Accept header capabilities using req.accepts.
🎯 Interview Key Takeaway
Use req.accepts() to evaluate client Accept header preferences and serve matching payload formats.
#req.accepts#Content Negotiation#Intermediate
Back to all Express JS Questions→