Node.jsアプリケーションにおいてMySQLにデータを入力(INSERT)してみます。
本記事ではexpress-generatorを利用しています。下記関連ページを参照してexpress-generatorモジュールをインストールしておいて下さい。
関連ページ
今回は下記のような簡単なアプリケーションを作成しています。
フォーム画面(localhost:3000/add)にtarouと入力してPOSTボタンをクリックすると、
トップページ(localhost:3000/)に戻りデータベースに値が入力されていることを確認できます。バリデーションの処理などもおこなっています。
MySQLとの接続、MySQLのテーブル構造などは下記のページを参照下さい。
まず雛形として「myproject」という名前のプロジェクトを作成します。テンプレートエンジンとしてEJSを利用するので、オプションに「-e」を設定しています。
1 |
express -e myproject |
依存するモジュールをインストールしておきます。
1 |
npm install |
mysqlおよびexpress-validatorモジュールをインストールします。
1 |
npm install --save mysql express-validator |
package.jsonのdependenciesの項目を確認すると下記のようになっています。
1 2 3 4 5 6 7 8 9 10 |
"dependencies": { "cookie-parser": "~1.4.3", "debug": "~2.6.9", "ejs": "~2.5.7", "express": "~4.16.0", "express-validator": "^5.3.1", "http-errors": "~1.6.2", "morgan": "~1.9.0", "mysql": "^2.16.0" } |
add.ejsのファイルのみを新規作成しています(users.jsなどは雛形で既に生成されているファイルです)。
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
const express = require('express'); const mysql = require('mysql'); const { check, validationResult } = require('express-validator/check'); const router = express.Router(); const mysql_setting = { host: '127.0.0.1', user: 'root', password: 'pass', database: 'sample01' } //localhost:3000/ router.get('/', function (req, res, next) { const connection = mysql.createConnection(mysql_setting); connection.connect(); connection.query('select * from name', function (error, results, fields) { if (error) throw error; res.render('index', { content: results }); }); connection.end(); }); //localhost:3000/add router.get('/add', function (req, res, next) { const data = { errorMessage: '' } res.render('./add', data); }); //localhost:3000/addへのPOST router.post('/add', [ check('name') .not().isEmpty().trim().escape().withMessage('名前を入力して下さい'), ], (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { const errors_array = errors.array(); res.render('./add', { errorMessage: errors_array, }) } else { const name = req.body.name; const post = { 'name': name }; const connection = mysql.createConnection(mysql_setting); connection.connect(); connection.query('INSERT INTO name SET ?', post, function (error, results, fields) { if (error) throw error; res.redirect('./'); console.log('ID:', results.insertId); }); connection.end(); } }) module.exports = router; |
38行目
.not().isEmpty()で未入力をチェックするバリデーションをおこない、.trim().escape()で前後の空白スペース削除およびエスケープ処理といったサニタイズをおこなっています。express-validatorモジュールについては下記のページを参照下さい。
例えばフォームに <script>alert(‘hoge’)</script> を入力すると、MySQLにはサニタイズされた下記のようなデータが保存されます。
1 |
<script>alert('hoge')</script> |
index.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!DOCTYPE html> <html> <head> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <a href="./add">追加</a> <table> <% for(let i in content) { %> <tr> <% let obj = content[i]; %> <td> <%= obj.id %> </td> <td> <%- obj.name %> </td> </tr> <% } %> </table> </body> </html> |
add.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<!DOCTYPE html> <html> <head> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <form action="/add" method="post"> <input type="text" name="name" value="名前"> <button type="submit" name="button">POST</button> </form> <% if(errorMessage) { %> <ul> <% for (let n in errorMessage) { %> <li> <%= errorMessage[n].msg %> </li> <% } %> </ul> <% } %> </body> </html> |
次ページ