Express content negotiation functions.
$ npm install express-negotiate
Require the module to add the request.negotiate method:
var express =negotiate = ;
Then use in the route handler:
Each handler key is either a full mimetype string, or a file extension string.
To prioritise handlers, simply append a quality in the same notation as the client uses when specifying an Accept header:
Note that the handler priority is only used after the priorities specified by any Accept header in the request have been considered. A priority cannot be specified on the 'default' handler.
When the same handler can be used for multiple types, then they can be combined in the string:
If there are no acceptable handlers, and no 'default' handler is specified, then req.negotiate will throw a negotiate.NotAcceptable error. This can be caught and handled using express error handling:
In some cases, it is preferable to call next(err) rather than throw an error. If negotiate is passed the 'next' callback function, it will call that instead:
By parsing out any filename extension on the route, and passing this to req.negotiate, the client can force a particular Content-Type regardless of the Accept header.
Picking up the filename extension on a "catch-all" route is a little trickier. The following example uses a regex to achieve this:
(The MIT License)
Copyright (c) 2011 Chris Leishman <firstname.lastname@example.org>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.