Content negotiation is a mechanism that allows us to serve the best representation for a given response when several are available.
Note
You can read more about content negotiation on MDN at https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation.
There are two ways in which we can perform content negotiation with Express: by appending the format to the URL or by checking for the Accept
header field.
The first option requires us to change the URL path and add a format
placeholder at the end; for example, consider the following line of code:
app.get('/notes/:id.:format', …)
Then, in the route handlers, we can use a switch
statement to serve the different content types, as follows:
switch (req.params.format) { case 'json': res.send(note); break; case 'xml': res.set('Content-Type', 'application/xml'); res.end(convertToXml(note)); break; default: res.status(400).send({ 'error': 'unknown format' }); }