UNPKG

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