Aer*_*ang 3 node.js express body-parser
router.post('/action', bodyParser.text(), async (req, res) => {
try {
body = JSON.parse(req.body);
// ...
res.send('ok');
} catch (e) {
res.send('not ok');
}
});
Run Code Online (Sandbox Code Playgroud)
我可以有上面的代码,Content-Type: 'text/plain'也可以有下面的代码Content-Type: 'application/json',但现在我需要同时支持它们,怎么办?bodyParser 中是否有支持“text/plain”和“application/json”的选项?
router.post('/action', bodyParser.json(), async (req, res) => {
try {
body = req.body;
// ...
res.send('ok');
} catch (e) {
res.send('not ok');
}
});
Run Code Online (Sandbox Code Playgroud)
没关系,我发现了这一点:
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');
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2319 次 |
| 最近记录: |