Build a JSON Body-Parsing Middleware in Node.js

Build a JSON Body-Parsing Middleware in Node.js

The Express JSON body-parsing middleware

const { json } = require('express');

app.post('/', json(), (req, res) => {
console.log(req.body);
// ...
});

The middleware skeleton

function parseJSON(req, res, next) {
req.body = {};
next();
}

Verify the payload encoding

function parseJSON(req, res, next) {
req.body = {};

if (req.headers['content-type'] === 'application/json') {
// ...
}

next();
}

Gather the payload chunks

function parseJSON(req, res, next) {
req.body = {};

if (req.headers['content-type'] === 'application/json') {
let data = '';

req.on('data', chunk => {
data += chunk;
});

req.on('end', () => {
// ...
});
}

next();
}

Parse the payload

function parseJSON(req, res, next) {
req.body = {};

if (req.headers['content-type'] === 'application/json') {
let data = '';

req.on('data', chunk => {
data += chunk;
});

req.on('end', () => {
req.body = JSON.parse(data);
});
}

next();
}

Change the function’s flow

function parseJSON(req, res, next) {
req.body = {};

if (req.headers['content-type'] === 'application/json') {
let data = '';

req.on('data', chunk => {
data += chunk;
});

req.on('end', () => {
req.body = JSON.parse(data);
next();
});
} else {
next();
}
}

Handle parsing errors

function parseJSON(req, res, next) {
req.body = {};

if (req.headers['content-type'] === 'application/json') {
let data = '';

req.on('data', chunk => {
data += chunk;
});

req.on('end', () => {
try {
req.body = JSON.parse(data);
next();
} catch(error) {
next();
}
});
} else {
next();
}
}

function parseJSON(req, res, next) {
req.body = {};

if (req.headers['content-type'] === 'application/json') {
let data = '';

req.on('data', chunk => {
data += chunk;
});

req.on('end', () => {
try {
req.body = JSON.parse(data);
} catch(error) {
// Ignore the error
} finally {
next();
}
});
} else {
next();
}
}

Test the middleware

function parseJSON(req, res, next) {
// ...
}

module.exports = parseJSON;

const express = require('express');
const parseJSON = require('./parseJSON');

const app = express();

app.post('/', parseJSON, (req, res) => {
console.log(req.body);
res.sendStatus(200);
});

app.listen(3000);

curl -X POST -H 'Content-Type: text/plain' -d '{"name":"John"}' 127.0.0.1:3000

curl -X POST -H 'Content-Type: application/json' -d 'name=John' 127.0.0.1:3000

curl -X POST -H 'Content-Type: application/json' -d '{"name":"John"}' 127.0.0.1:3000

What’s next?