- Notifications
You must be signed in to change notification settings - Fork0
Higher-level content negotiation
License
Morin3/accepts
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Higher level content negotiation based onnegotiator.Extracted fromkoa for general use.
In addition to negotiator, it allows:
- Allows types as an array or arguments list, ie
(['text/html', 'application/json'])
as well as('text/html', 'application/json')
. - Allows type shorthands such as
json
. - Returns
false
when no types match - Treats non-existent headers as
*
This is aNode.js module available through thenpm registry. Installation is done using thenpm install
command:
$ npm install accepts
varaccepts=require('accepts')
Create a newAccepts
object for the givenreq
.
Return the first accepted charset. If nothing incharsets
is accepted,thenfalse
is returned.
Return the charsets that the request accepts, in the order of the client'spreference (most preferred first).
Return the first accepted encoding. If nothing inencodings
is accepted,thenfalse
is returned.
Return the encodings that the request accepts, in the order of the client'spreference (most preferred first).
Return the first accepted language. If nothing inlanguages
is accepted,thenfalse
is returned.
Return the languages that the request accepts, in the order of the client'spreference (most preferred first).
Return the first accepted type (and it is returned as the same text as whatappears in thetypes
array). If nothing intypes
is accepted, thenfalse
is returned.
Thetypes
array can contain full MIME types or file extensions. Any valuethat is not a full MIME type is passed torequire('mime-types').lookup
.
Return the types that the request accepts, in the order of the client'spreference (most preferred first).
This simple example shows how to useaccepts
to return a different typedrespond body based on what the client wants to accept. The server lists it'spreferences in order and will get back the best match between the client andserver.
varaccepts=require('accepts')varhttp=require('http')functionapp(req,res){varaccept=accepts(req)// the order of this list is significant; should be server preferred orderswitch(accept.type(['json','html'])){case'json':res.setHeader('Content-Type','application/json')res.write('{"hello":"world!"}')breakcase'html':res.setHeader('Content-Type','text/html')res.write('<b>hello, world!</b>')breakdefault:// the fallback is text/plain, so no need to specify it aboveres.setHeader('Content-Type','text/plain')res.write('hello, world!')break}res.end()}http.createServer(app).listen(3000)
You can test this out with the cURL program:
curl -I -H'Accept: text/html' http://localhost:3000/