LoginSignup
21
15

More than 5 years have passed since last update.

Express.jsで、配列型のフォームデータを受け取る方法

Posted at
  • Express.js: 4.13.4
  • body-parser: 1.13.3

以下の様なフォームで、textという名前のデータを配列で送信したい。

<!DOCTYPE html>
<title>テスト</title>
<form method="post" action="/form">
  <label>テキスト1: 
    <input type="text" name="text[]" value="text1">
  </label>
  <label>テキスト2: 
    <input type="text" name="text[]" value="text2">
  </label>
  <input type="submit" value="送信">
</form>

Kobito.GLSgPS.png

express-generatorでExpress.jsアプリケーションの雛形を作ると、フォームのボディをパースするミドルウェアとしてbody-parserが使われるが、デフォルトでは

app.use(bodyParser.urlencoded({ extended: false }));

となっている。ここを、

app.use(bodyParser.urlencoded({ extended: true }));

としてあげと、req.body.textが配列になる。以下の様にreq.body.textを返すようにしてあげると、

router.post('/form', function(req, res, next) {
  res.json({ texts: req.body.text });
});

以下のようなJSONがクライアントに返される。

{"texts":["text1","text2"]}
21
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
15