Content negotiation
A route supports JSON and HTML and needs to select the representation requested by the client.
Express.js · Module
req.accepts() checks candidate response types against the request's Accept header and returns the best match. It returns false when none of the supplied types is acceptable.
Call req.accepts() with one or more candidate content types. Express compares them with the request's Accept header and returns the best matching candidate; when nothing matches, it returns false so the application can send a 406 response.
req.accepts(types)| Name | Type | Description |
|---|---|---|
types | String | String[] | The content type or types to test: a MIME type, extension name, comma-delimited list, or array. |
String | false
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const match = req.accepts(['json', 'html']);
if (match === 'json') return res.json({ message: 'Hello' });
if (match === 'html') return res.type('html').send('<h1>Hello</h1>');
res.status(406).send('Not Acceptable');
});
app.listen(3000);Run the server, then request / with an Accept header such as application/json or text/html.
A route supports JSON and HTML and needs to select the representation requested by the client.
An endpoint should reject requests that cannot accept any supported response format.
A handler wants concise candidate names instead of repeating full MIME strings.
It checks candidate MIME types or extensions against the request's Accept header and returns the best match. If no candidate is acceptable, it returns false.
Follow-up: How would you handle a client that accepts both JSON and HTML? Pass both candidates as an array and branch on the returned best match.
The argument may be a MIME type, an extension, a comma-delimited list, or an array. For multiple candidates, Express chooses the best acceptable match.
Follow-up: Why might an array be preferable to a comma-delimited string? It keeps candidate values structurally separate and is easier to build dynamically.
The method bases its decision on the request's Accept HTTP header. A wildcard or quality-weighted header can affect which candidate is selected.
Follow-up: What should the route do when the header excludes every candidate? Return a 406 response because no requested representation can be served.
req.acceptsCharsets()req.acceptsEncodings()req.acceptsLanguages()req.get()res.format()