Express body-parser 支持 Content-Type 'text/plain' 和 'application/json'

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)

Aer*_*ang 5

没关系,我发现了这一点:

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)