Skip to content

Instantly share code, notes, and snippets.

@RyAndrew
Created September 29, 2021 14:50
Show Gist options
  • Save RyAndrew/00636401f2171b0a229d3f9561680195 to your computer and use it in GitHub Desktop.
Save RyAndrew/00636401f2171b0a229d3f9561680195 to your computer and use it in GitHub Desktop.
node request json body parser
//souce: https://blog.logrocket.com/forget-express-js-opt-for-these-alternatives-instead/
//usage
parsed = await req.requestBodyJson();
//utility fn
function requestBodyJson(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', (data) => {
// This function is called as chunks of body are received
body += data;
});
req.on('end', () => {
// This function is called once the body has been fully received
let parsed;
try {
parsed = JSON.parse(body);
} catch (e) {
reject(e);
return;
}
resolve(parsed);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment