Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/middlewares.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,6 @@ function createBodyParser(defaultType, beforeReturn) {
}

const length = req.headers['content-length'];
// skip reading empty body
if(length == '0') {
return next();
}

if(options.simpleType) {
const semicolonIndex = type.indexOf(';');
Expand All @@ -204,6 +200,13 @@ function createBodyParser(defaultType, beforeReturn) {
}
}

// an empty body still has to produce this parser's empty value the way express does -
// {} for json and urlencoded, '' for text, an empty Buffer for raw - rather than leaving
// req.body as the placeholder object. there is nothing to read, so run the tail directly
if(length == '0') {
return beforeReturn(req, res, next, options, Buffer.alloc(0));
}

// skip reading too large body
if(length && +length > options.limit) {
return next(new Error('Request entity too large'));
Expand Down
49 changes: 49 additions & 0 deletions tests/tests/middlewares/empty-body-parsers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// must give an empty body the same shape express does, for every body parser

const express = require("express");

const app = express();

app.post('/json', express.json(), (req, res) => {
res.json({ type: typeof req.body, isBuffer: Buffer.isBuffer(req.body), value: JSON.stringify(req.body) });
});

app.post('/urlencoded', express.urlencoded({ extended: false }), (req, res) => {
res.json({ type: typeof req.body, keys: Object.keys(req.body).length });
});

app.post('/text', express.text(), (req, res) => {
res.json({ type: typeof req.body, length: req.body.length });
});

app.post('/raw', express.raw(), (req, res) => {
res.json({ isBuffer: Buffer.isBuffer(req.body), length: req.body.length });
});

function empty(path, contentType) {
return fetch(`http://localhost:13333${path}`, {
method: 'POST',
body: '',
headers: { 'Content-Type': contentType }
}).then(r => r.text());
}

app.listen(13333, async () => {
console.log('Server is running on port 13333');

console.log(await empty('/json', 'application/json'));
console.log(await empty('/urlencoded', 'application/x-www-form-urlencoded'));
console.log(await empty('/text', 'text/plain'));
console.log(await empty('/raw', 'application/octet-stream'));

// a non-empty body must still parse the same way afterwards
const after = await fetch('http://localhost:13333/json', {
method: 'POST',
body: '{"a":1}',
headers: { 'Content-Type': 'application/json' }
});
console.log(await after.text());

await new Promise(resolve => setTimeout(resolve, 100));
process.exit(0);
});
Loading