forked from fastify/fastify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.js
42 lines (36 loc) · 1.14 KB
/
parser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
'use strict'
const fastify = require('../fastify')()
const jsonParser = require('fast-json-body')
const qs = require('qs')
// Handled by fastify
// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/json' http://localhost:3000/
// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/jsoff' http://localhost:3000/
fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {
jsonParser(payload, function (err, body) {
done(err, body)
})
})
// curl -X POST -d 'hello=world' -H'Content-type: application/x-www-form-urlencoded' http://localhost:3000/
fastify.addContentTypeParser('application/x-www-form-urlencoded', function (request, payload, done) {
var body = ''
payload.on('data', function (data) {
body += data
})
payload.on('end', function () {
try {
const parsed = qs.parse(body)
done(null, parsed)
} catch (e) {
done(e)
}
})
payload.on('error', done)
})
fastify
.post('/', function (req, reply) {
reply.send(req.body)
})
fastify.listen(3000, err => {
if (err) throw err
console.log(`server listening on ${fastify.server.address().port}`)
})