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.
Files changed (2) hide show
  1. package/index.js +29 -27
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,36 +1,38 @@
1
- function reqBodyParser(options = {}) {
2
- const MAX_SIZE = options.limit || 1e6;
1
+ function reqBodyParser(req, res, next) {
2
+ // Only parse JSON requests
3
+ const contentType = req.headers['content-type'];
3
4
 
4
- return function (req, res, next) {
5
- const contentType = req.headers['content-type'];
5
+ if (!contentType || !contentType.includes('application/json')) {
6
+ return next();
7
+ }
6
8
 
7
- if (!contentType || !contentType.includes('application/json')) {
8
- return next();
9
- }
9
+ let body = '';
10
10
 
11
- let body = '';
11
+ req.on('data', chunk => {
12
+ body += chunk.toString();
13
+ });
12
14
 
13
- req.on('data', chunk => {
14
- body += chunk;
15
- if (body.length > MAX_SIZE) {
16
- res.status(413).json({ error: 'Payload too large' });
17
- req.destroy();
18
- }
19
- });
15
+ req.on('end', () => {
16
+ if (!body) {
17
+ req.body = {};
18
+ return next();
19
+ }
20
20
 
21
- req.on('end', () => {
22
- try {
23
- req.body = body ? JSON.parse(body) : {};
24
- next();
25
- } catch {
26
- res.status(400).json({ error: 'Invalid JSON' });
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
- req.on('error', () => {
31
- res.status(400).json({ error: 'Request error' });
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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "req-body-parser",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "A lightweight JSON body parser middleware for Express",
5
5
  "main": "index.js",
6
6
  "scripts": {