LoginSignup
8
8

More than 5 years have passed since last update.

Mac(Yosemite)でNode.jsとExpress 4を使って、MySQLに繋がるwebアプリを作ってみる

Last updated at Posted at 2015-03-18

Express4を使って、Node.jsアプリを作り始めてみました。
その際の荒々しいメモになります。

前提

  • Yosemiteを使っている
  • MySQLはインストール済(homebrewからでもなんでも) - 参考 || 参考
  • node, npmが入っている(homebrewからでもなんでも) - 参考

まずはnpmでexpressコマンドをインストール

今回はexpress4を使ってみましたが、3までとやり方が異なる様です。
詳細などはこちら

$ npm install -g express-generator
/usr/local/bin/express -> /usr/local/lib/node_modules/express-generator/bin/express
express-generator@4.12.1 /usr/local/lib/node_modules/express-generator
├── sorted-object@1.0.0
├── commander@2.6.0
└── mkdirp@0.5.0 (minimist@0.0.8)

expressでプロジェクトを作成

expressコマンドについてはこちら

$ express -e -c stylus myapp(プロジェクト名)

   create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/images
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.styl
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/users.js
   create : myapp/views
   create : myapp/views/index.ejs
   create : myapp/views/error.ejs
   create : myapp/bin
   create : myaoo/bin/www

   install dependencies:
     $ cd myapp && npm install

   run the app:
     $ DEBUG=myapp:* ./bin/www

   create : myapp/public/javascripts

とりあえずMacのMySQLに繋ぐ

$ mysql -u root

mysql> show databases;
+---------------------------+
| Database                  |
+---------------------------+
| information_schema        |
| mysql                     |
| performance_schema        |
| test                      |
+---------------------------+
10 rows in set (0.04 sec)

適当なDBとユーザーを作ってみる

mysql> create database mydb;
Query OK, 1 row affected (0.01 sec)

mysql> grant all on mydb.* to watashi@localhost;
Query OK, 0 rows affected (0.02 sec)

mysql> set password for watashi@localhost=password('hogehoge');
Query OK, 0 rows affected (0.01 sec)

mysql> exit;
Bye

とりあえずテスト用のテーブルを作ってみる

sql/table.sql
create table users (
    name varchar(255) primary key,
    email text not null
);
sql/test_data.sql
insert into users values ('admin', 'admin@example.com');
insert into users values ('hoge', 'hoge@hoge.hoge');
insert into users values ('user', 'user@user.user');
$ mysql -u watashi -p mydb
Enter password: hogehoge

mysql> show databases;
+---------------------+
| Database            |
+---------------------+
| information_schema  |
| mydb                |
| test                |
+---------------------+
3 rows in set (0.01 sec)
  • make table
mysql> source sql/table.sql;
Query OK, 0 rows affected (0.10 sec)

mysql> show tables;
+-------------------------------+
| Tables_in_mydb                |
+-------------------------------+
| users                         |
+-------------------------------+
1 row in set (0.00 sec)
  • insert test data
mysql> source sql/test_data.sql;
Query OK, 1 row affected (0.04 sec)

Query OK, 1 row affected (0.00 sec)

Query OK, 1 row affected (0.00 sec)

mysql> select * from users;
+-------+-------------------+
| name  | email             |
+-------+-------------------+
| admin | admin@example.com |
| hoge  | hoge@hoge.hoge    |
| user  | user@user.user    |
+-------+-------------------+
3 rows in set (0.00 sec)
mysql> exit
Bye

とりあえず接続

まず、MySQL に接続するためのパッケージを package.json に追加します。

package.json
{
  "name": "myapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.12.0",
    "cookie-parser": "~1.3.4",
    "debug": "~2.1.1",
    "jade": "*",
    "express": "~4.12.2",
    "morgan": "~1.5.1",
    "serve-favicon": "~2.2.0",
    "stylus": "0.42.3",
    "mysql": "*"
  }
}
app.js
 *
 *
var mysql = require('mysql');
 *
 *
var connection = mysql.createConnection({
  host: process.env.DB_HOST || 'localhost', //localhostで立ち上げる場合
  user: process.env.DB_USER || 'watashi',
  password: process.env.DB_PASS || 'hogehoge',
  database: process.env.DB_NAME || 'mydb'
});
 *
 *

package.jsonに記載した内容をインストール

$ npm install
------
debug@2.1.3 node_modules/debug
└── ms@0.7.0
 *
 *
 *

環境変数でmysqlへの接続を管理する場合は

これで、node app 起動時に MySQL に接続するようになります。
なお、接続先 DB の情報は環境変数で与えることもできます。

run.sh
#!/bin/sh
 *
 *

export DB_HOST="localhost"
export DB_USER="watashi"
export DB_PASS="hogehoge"
export DB_NAME="myapp"

 *
 *

MySQLにアクセス

connection.query()を使ってアクセスする

app.js
app.get('/users', function (req, res) {
  connection.query('select * from users', function (err, rows) {
    res.render('users', { title: 'hoge', users: rows });
  });
});

poolの利用

app.js
 *
 *

var pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'watashi',
  password: process.env.DB_PASS || 'hogehoge',
  database: process.env.DB_NAME || 'mydb'
});

 *
 *

app.get('/users', function (req, res) {
  pool.query('select * from users', function (err, rows) {
    res.render('users', { title: 'hoge', users: rows });
  });
});

まだ途中ですが、とりあえずmysqlに繋ぐところまではできました。
続きます。

Reference

8
8
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
8
8