Created
September 29, 2021 14:50
-
-
Save RyAndrew/00636401f2171b0a229d3f9561680195 to your computer and use it in GitHub Desktop.
node request json body parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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