UNPKG

1.71 kBJavaScriptView Raw
1'use strict'
2
3const fastify = require('../fastify')({ logger: true })
4const jsonParser = require('fast-json-body')
5const querystring = require('node:querystring')
6
7// Handled by fastify
8// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/json' http://localhost:3000/
9
10// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/jsoff' http://localhost:3000/
11fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {
12 jsonParser(payload, function (err, body) {
13 done(err, body)
14 })
15})
16
17// curl -X POST -d 'hello=world' -H'Content-type: application/x-www-form-urlencoded' http://localhost:3000/
18fastify.addContentTypeParser('application/x-www-form-urlencoded', function (request, payload, done) {
19 let body = ''
20 payload.on('data', function (data) {
21 body += data
22 })
23 payload.on('end', function () {
24 try {
25 const parsed = querystring.parse(body)
26 done(null, parsed)
27 } catch (e) {
28 done(e)
29 }
30 })
31 payload.on('error', done)
32})
33
34// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/vnd.custom+json' http://localhost:3000/
35fastify.addContentTypeParser(/^application\/.+\+json$/, { parseAs: 'string' }, fastify.getDefaultJsonParser('error', 'ignore'))
36
37// remove default json parser
38// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/json' http://localhost:3000/ is now no longer handled by fastify
39fastify.removeContentTypeParser('application/json')
40
41// This call would remove any content type parser
42// fastify.removeAllContentTypeParsers()
43
44fastify
45 .post('/', function (req, reply) {
46 reply.send(req.body)
47 })
48
49fastify.listen({ port: 3000 }, err => {
50 if (err) {
51 throw err
52 }
53})