node.js言語のHTTPウェブサーバーライブラリ、express.jsにおいて、POSTデータ(body)を取得しようとすると TypeError: Cannot read property xx of undefined のエラーが出る場合があります。
express.jsにhttp postをリクエストボディつきで送ると、TypeError: Cannot read property xx of undefined
エラーになります。
curl http://192.168.0.110:8111/config -X POST -d 'content=hogehogehoge'
まずパッケージをインストールします
npm install --save body-parser
以下を追記します。
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
これで、req.body.value
でhttp postのデータが取得できるようになりました。
以下では上記のcurlの通り、content
を取得するためにreq.body.content
をしています。
app.post('/config', async (req, res, next) => {
try {
console.log(req.body.content) ;
res.send("something here.")
next();
} catch (error) {
next(error);
}
});
express.jsのバージョンによってはやり方が変わるようです。
javascript – How to retrieve POST query parameters? – Stack Overflow