-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
45 lines (43 loc) · 1.34 KB
/
Copy pathindex.js
File metadata and controls
45 lines (43 loc) · 1.34 KB
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
43
44
45
const FORM_URLENCODED = 'application/x-www-form-urlencoded'
const FORM_JSON = 'application/json'
const FORM_DATA = 'multipart/form-data'
const { RequestMethods } = require('./constants')
const qs = require('querystring');
const bodyParser = (req, res, next) => {
if (req.method.toString() === RequestMethods.PUT || req.method.toString() === RequestMethods.POST) {
const REQ_HEADER_CONTENT_TYPE = req.headers['content-type']
if(!REQ_HEADER_CONTENT_TYPE) return next(new Error('cannot parse body data of null'))
if (REQ_HEADER_CONTENT_TYPE.includes(FORM_URLENCODED)) {
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', () => {
req.body = qs.parse(body)
return next()
})
} else if (REQ_HEADER_CONTENT_TYPE.includes(FORM_JSON)) {
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', () => {
req.body = JSON.parse(body)
return next()
})
} else if (REQ_HEADER_CONTENT_TYPE.includes(FORM_DATA)) {
return next(`Doesn't support ${FORM_DATA} yet.`)
}
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', () => {
req.body = JSON.parse(body)
return next()
})
}else{
next();
}
}
module.exports = bodyParser