req-body-parser 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +29 -27
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,36 +1,38 @@
|
|
|
1
|
-
function reqBodyParser(
|
|
2
|
-
|
|
1
|
+
function reqBodyParser(req, res, next) {
|
|
2
|
+
// Only parse JSON requests
|
|
3
|
+
const contentType = req.headers['content-type'];
|
|
3
4
|
|
|
4
|
-
|
|
5
|
-
|
|
5
|
+
if (!contentType || !contentType.includes('application/json')) {
|
|
6
|
+
return next();
|
|
7
|
+
}
|
|
6
8
|
|
|
7
|
-
|
|
8
|
-
return next();
|
|
9
|
-
}
|
|
9
|
+
let body = '';
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
req.on('data', chunk => {
|
|
12
|
+
body += chunk.toString();
|
|
13
|
+
});
|
|
12
14
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
}
|
|
19
|
-
});
|
|
15
|
+
req.on('end', () => {
|
|
16
|
+
if (!body) {
|
|
17
|
+
req.body = {};
|
|
18
|
+
return next();
|
|
19
|
+
}
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
}
|
|
28
|
-
}
|
|
21
|
+
try {
|
|
22
|
+
req.body = JSON.parse(body);
|
|
23
|
+
next();
|
|
24
|
+
} catch (err) {
|
|
25
|
+
res.status(400).json({
|
|
26
|
+
error: 'Invalid JSON'
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
});
|
|
29
30
|
|
|
30
|
-
|
|
31
|
-
|
|
31
|
+
req.on('error', () => {
|
|
32
|
+
res.status(400).json({
|
|
33
|
+
error: 'Request stream error'
|
|
32
34
|
});
|
|
33
|
-
};
|
|
35
|
+
});
|
|
34
36
|
}
|
|
35
37
|
|
|
36
|
-
module.exports = reqBodyParser;
|
|
38
|
+
module.exports = reqBodyParser;
|