I would like to check if the type that is requested by my client is JSON or HTML, as I want my route to satisfy both human and machine needs.
I have read the Express
To throw my hat in the ring, I wanted easily readable routes without having .json
suffixes everywhere or having to have each route hide these details in the handler.
router.get("/foo", HTML_ACCEPTED, (req, res) => res.send("baz
qux
"))
router.get("/foo", JSON_ACCEPTED, (req, res) => res.json({foo: "bar"}))
Here's how those middlewares work.
function HTML_ACCEPTED (req, res, next) { return req.accepts("html") ? next() : next("route") }
function JSON_ACCEPTED (req, res, next) { return req.accepts("json") ? next() : next("route") }
Personally I think this is quite readable (and therefore maintainable).
$ curl localhost:5000/foo --header "Accept: text/html"
baz
qux
$ curl localhost:5000/foo --header "Accept: application/json"
{"foo":"bar"}
Notes: