req.accepts() checks a client's Accept header against the content types you offer, and
returns the best match, or false if nothing matches.
Syntax
req.accepts(types)
Example
const express = require("express");
const app = express();
const PORT = 4700;
app.get("/report", (req, res) => {
const type = req.accepts(["json", "html"]);
if (type === "json") {
return res.json({ report: "monthly-sales" });
}
if (type === "html") {
return res.send("<h1>Monthly Sales Report</h1>");
}
res.status(406).send("Not Acceptable");
});
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
A request with Accept: application/json gets a JSON response; Accept: text/html gets
HTML.
Use cases
- Content negotiation between JSON, HTML, XML, and other formats.
- Serving the same endpoint differently depending on the client.
- Returning
406 Not Acceptablefor unsupported formats.