Reputation: 9227
router.post('/action', bodyParser.text(), async (req, res) => {
try {
body = JSON.parse(req.body);
// ...
res.send('ok');
} catch (e) {
res.send('not ok');
}
});
I could have the above code for Content-Type: 'text/plain'
and I could have the below code for Content-Type: 'application/json'
, but now I need to support them both, how? Is there an option in bodyParser that supports both 'text/plain' and 'application/json'?
router.post('/action', bodyParser.json(), async (req, res) => {
try {
body = req.body;
// ...
res.send('ok');
} catch (e) {
res.send('not ok');
}
});
Upvotes: 3
Views: 2505
Reputation: 9227
Never mind I figured this out:
router.post('/action', bodyParser.text({
type: ['json', 'text']
}), async function(req, res) {
try {
body = typeof req.body === 'string' ? JSON.parse(req.body) : req.body;
// ...
res.send('ok');
} catch (e) {
res.send('not ok');
}
});
Upvotes: 5