Node.js + Express で、POSTされてきたフォームの本文をそのまま取得したかったのでメモ。
body-parserのverify:rawBodySaverオプションを使う必要がある。
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
let rawBodySaver = function(req, res, buf, encoding) {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
};
app.use(bodyParser.json({verify: rawBodySaver}));
app.use(bodyParser.urlencoded({verify: rawBodySaver, extended: true}));
app.use(bodyParser.raw({verify: rawBodySaver, type: '*/*'}));
app.use(function(req, res){
console.log(req.rawBody); //rawBody
res.send(req.rawBody); //rawBody
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log('App Running...');
});
そのまま生のBody本文使う需要なんかないんだろうな。
JSON変換のサンプルはゴロゴロ見つかったが。