Add an accepts parser to Fastify.
npm i @fastify/accepts
Plugin version | Fastify version |
---|---|
^5.x |
^5.x |
^4.x |
^4.x |
^2.x |
^3.x |
^1.x |
^2.x |
^1.x |
^1.x |
Please note that if a Fastify version is out of support, then so are the corresponding version(s) of this plugin in the table above. See Fastify's LTS policy for more details.
const fastify = require('fastify')
const Boom = require('@hapi/boom')
fastify.register(require('@fastify/accepts'))
fastify.post('/', function (req, reply) {
const accept = req.accepts() // Accepts object
switch(accept.type(['json', 'html'])) {
case 'json':
reply.type('application/json').send({hello: 'world'})
break
case 'html':
reply.type('text/html').send('<b>hello, world!</b>')
break
default:
reply.send(Boom.notAcceptable('unacceptable'))
break
}
})
See accepts package for all available APIs.
This plugin adds to Request
object all Accepts
object methods.
fastify.post('/', function (req, reply) {
req.charset(['utf-8'])
req.charsets()
req.encoding(['gzip', 'compress'])
req.encodings()
req.language(['es', 'en'])
req.languages()
req.type(['image/png', 'image/tiff'])
req.types()
})
decorateReply
Iftrue
, theReply
object will be decorated with therequestAccepts
,requestTypes
,requestCharsets
,requestEncodings
, andrequestLanguages
methods, which will return the corresponding values from theRequest
object. Default:false
.
Licensed under MIT.