UNPKG

1.13 kBJavaScriptView Raw
1'use strict'
2
3const fastify = require('../fastify')()
4const jsonParser = require('fast-json-body')
5const qs = require('qs')
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 (req, done) {
12 jsonParser(req, 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 (req, done) {
19 var body = ''
20 req.on('data', function (data) {
21 body += data
22 })
23 req.on('end', function () {
24 try {
25 const parsed = qs.parse(body)
26 done(null, parsed)
27 } catch (e) {
28 done(e)
29 }
30 })
31 req.on('error', done)
32})
33
34fastify
35 .post('/', function (req, reply) {
36 reply.send(req.body)
37 })
38
39fastify.listen(3000, err => {
40 if (err) throw err
41 console.log(`server listening on ${fastify.server.address().port}`)
42})