LoginSignup
37
33

More than 3 years have passed since last update.

node.js(express)のbody-parserを理解する

Posted at

bodyParserとは、

HTML(ejs)のformのinputに入力された値を受け取れるようにするものです。

例↓

<form action="/" method="post">
    <p>
      <input type="text" name="message">
      <input type="submit" value="送信">
    </p>
</form>

この例の場合は、


<input type="text" name="message">

の値を取得します。

inputの値をどう取得するの?

inputにnameを指定して、javascriptで


req.body.[inputのnameに指定した値]

というように書く事でinputの値を受け取れるようになります。

上の例のnameにmessageを指定した例ですと、下のように書けば値を受け取れます。


req.body.message

body-parserをインストールしなければ、上のコードを書いてもエラーになります。

body-parserを使った簡単なアプリの例

html(ejs)でフォームを作成します。

index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta http-equiv="content-type" content="text/html" charset="UTF-8">
        <title><%=title %></title>
        <link type="text/css" href="./style.css" rel="stylesheet">
    </head>

    <body>
        <head>
            <h1><%=title %></h1>
        </head>
        <div role="main">
            <p><%-content %></p>
            <form action="/" method="post">
                <p><input type="text" name="message">
                   <input type="submit" value="送信"></p>
            </form>
        </div>
    </body>
</html>

このフォームを送信したら(input type="submitのボタンを押したら)、actionへ移動します。

index.js
var express = require('express');
var ejs = require("ejs");

var app = express();
app.engine('ejs', ejs.renderFile);
app.use(express.static('public'));

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));

// ※トップページ
app.get('/', (req, res) => {
    var msg = 'This is Express Page!<br>' + '※メッセージを書いて送信して下さい。';
    res.render('index.ejs',
    {
        title: 'Index',
        content: msg,
    });
});

// ※POST送信の処理
app.post('/', (req, res) => {
    var msg = 'This is Posted Page!<br>' + 'あなたは「<b>' + req.body.message + '</b>」と送信しました。';
    res.render('index.ejs',
        {
            title: 'Posted',
            content: msg,
        });
});

var server = app.listen(3000,() => {
    console.log('Server is runnning!');
})

javascriptでpost送信されたあと、
body-parserを使ってreq.body.messageで値を受け取り、
それを表示させています。

作ったアプリ↓

スクリーンショット 2020-02-16 21.37.22.png

”ありがとう”という値を送信しました。
それを受け取っていることが分かります。

終わりに

参考にした本↓
https://www.amazon.co.jp/Node-js%E8%B6%85%E5%85%A5%E9%96%80-%E7%AC%AC2%E7%89%88-%E6%8E%8C%E7%94%B0-%E6%B4%A5%E8%80%B6%E4%B9%83/dp/4798055220/ref=asc_df_4798055220/?tag=jpgo-22&linkCode=df0&hvadid=295723231663&hvpos=1o1&hvnetw=g&hvrand=2502203059216170870&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=1009243&hvtargid=pla-526606012765&psc=1&th=1&psc=1

の212ページ

37
33
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
37
33