プログラミング

express.jsでPOSTデータ(body)を取得しようとすると TypeError: Cannot read property xx of undefined

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

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です