UNPKG

4.55 kBMarkdownView Raw
1<h1 align="center">Fastify</h1>
2
3## Content Type Parser
4Natively, Fastify only supports `'application/json'` and `'text/plain'` content types. The default charset is `utf-8`. If you need to support different content types, you can use the `addContentTypeParser` API. *The default JSON and/or plain text parser can be changed.*
5
6As 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 register it will be available only in that scope and its children.
7
8Fastify adds automatically the parsed request payload to the [Fastify request](https://github.com/fastify/fastify/blob/master/docs/Request.md) object, you can reach it with `request.body`.
9
10### Usage
11```js
12fastify.addContentTypeParser('application/jsoff', function (req, done) {
13 jsoffParser(req, function (err, body) {
14 done(err, body)
15 })
16})
17// handle multiple content types as the same
18fastify.addContentTypeParser(['text/xml', 'application/xml'], function (req, done) {
19 xmlParser(req, function (err, body) {
20 done(err, body)
21 })
22})
23// async also supported in Node versions >= 8.0.0
24fastify.addContentTypeParser('application/jsoff', async function (req) {
25 var res = await new Promise((resolve, reject) => resolve(req))
26 return res
27})
28```
29
30You can also use the `hasContentTypeParser` API to find if a specific content type parser already exists.
31
32```js
33if (!fastify.hasContentTypeParser('application/jsoff')){
34 fastify.addContentTypeParser('application/jsoff', function (req, done) {
35 //code to parse request body /payload for given content type
36 })
37}
38```
39
40#### Body Parser
41You can parse the body of the 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 `'string'` or `'buffer'`. If you use the `parseAs` option Fastify will internally handle the stream and perform some checks, such as the [maximum size](https://github.com/fastify/fastify/blob/master/docs/Server.md#factory-body-limit) of the body and the content length. If the limit is exceeded the custom parser will not be invoked.
42```js
43fastify.addContentTypeParser('application/json', { parseAs: 'string' }, function (req, body, done) {
44 try {
45 var json = JSON.parse(body)
46 done(null, json)
47 } catch (err) {
48 err.statusCode = 400
49 done(err, undefined)
50 }
51})
52```
53As you can see, now the function signature is `(req, body, done)` instead of `(req, done)`.
54
55See [`example/parser.js`](https://github.com/fastify/fastify/blob/master/examples/parser.js) for an example.
56
57##### Custom Parser Options
58+ `parseAs` (string): Either `'string'` or `'buffer'` to designate how the incoming data should be collected. Default: `'buffer'`.
59+ `bodyLimit` (number): The maximum payload size, in bytes, that the custom parser will accept. Defaults to the global body limit passed to the [`Fastify factory function`](https://github.com/fastify/fastify/blob/master/docs/Server.md#bodylimit).
60
61#### Catch All
62There are some cases where you need to catch all requests regardless of their content type. With Fastify, you just need to add the `'*'` content type.
63```js
64fastify.addContentTypeParser('*', function (req, done) {
65 var data = ''
66 req.on('data', chunk => { data += chunk })
67 req.on('end', () => {
68 done(null, data)
69 })
70})
71```
72
73In this way, all of the requests that do not have a corresponding content type parser will be handled by the specified function.
74
75This is also useful for piping the request stream. You can define a content parser like:
76
77```js
78fastify.addContentTypeParser('*', function (req, done) {
79 done()
80})
81```
82
83and then access the core HTTP request directly for piping it where you want:
84
85```js
86app.post('/hello', (request, reply) => {
87 reply.send(request.req)
88})
89```
90
91Here is a complete example that logs incoming [json line](http://jsonlines.org/) objects:
92
93```js
94const split2 = require('split2')
95const pump = require('pump')
96
97fastify.addContentTypeParser('*', (req, done) => {
98 done(null, pump(req, split2(JSON.parse)))
99})
100
101fastify.route({
102 method: 'POST',
103 url: '/api/log/jsons',
104 handler: (req, res) => {
105 req.body.on('data', d => console.log(d)) // log every incoming object
106 }
107})
108 ```
109
110For piping file uploads you may want to checkout [this plugin](https://github.com/fastify/fastify-multipart).
111
\No newline at end of file