As with the other APIs, addContentTypeParser
is encapsulated in the scope in which it is declared. This means that if you declare it in the root scope it will be available everywhere, while if you declare it inside a plugin it will be available only in that scope and its children.
Fastify automatically adds the parsed request payload to the object which you can access with request.body
.
You can also use the hasContentTypeParser
API to find if a specific content type parser already exists.
if (!fastify.hasContentTypeParser('application/jsoff')){
fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {
jsoffParser(payload, function (err, body) {
})
}
Body Parser
You can parse the body of a request in two ways. The first one is shown above: you add a custom content type parser and handle the request stream. In the second one, you should pass a parseAs
option to the addContentTypeParser
API, where you declare how you want to get the body. It could be of type 'string'
or 'buffer'
. If you use the parseAs
option, Fastify will internally handle the stream and perform some checks, such as the of the body and the content length. If the limit is exceeded the custom parser will not be invoked.
See example/parser.js
for an example.
Custom Parser Options
parseAs
(string): Either'string'
or to designate how the incoming data should be collected. Default:'buffer'
.bodyLimit
(number): The maximum payload size, in bytes, that the custom parser will accept. Defaults to the global body limit passed to theFastify factory function
.
Catch-All
There are some cases where you need to catch all requests regardless of their content type. With Fastify, you can just use the '*'
content type.
fastify.addContentTypeParser('*', function (request, payload, done) {
var data = ''
payload.on('end', () => {
done(null, data)
})
})
This is also useful for piping the request stream. You can define a content parser like:
and then access the core HTTP request directly for piping it where you want:
app.post('/hello', (request, reply) => {
})
Here is a complete example that logs incoming json line objects: