Node.js expressを使ってMysqlに接続してデータを表示する

node.jsのフレームワークExpressを利用して、Mysqlに接続するためのサンプルコードです。
環境
- OS CentOS Linux release 8.0.1905 (Core)
- node V10.16.3
- npm 6.9.0
- express 4.17.1
Express環境構築
下記の手順で構築してます。
npm init -y
npm i -D express
npm install -D express-generator
mysqlモジュールをインストールします
npm install --save mysql
接続用のDBとtableも作成しておきます。
## userというユーザーでログイン
mysql -u user -p
テスト用DB作成
mysql> create database testdb;
テスト用テーブル作成
mysql> use testdb;
mysql> create table title (id int, title varchar(10));
データ作成
mysql> insert into title values (1,'test1');
mysql> insert into title values (2,'test2');
.
.
mysql> insert into title values (5,'test5');
Mysqlモジュール使い方
mysqlモジュールを利用して作成したtableに接続します。
プロジェクト配下にapp.jsを作成して、下記のように編集します
const express = require('express')
const ejs = require('ejs')
const mysql = require('mysql')
const app = express()
app.set('ejs', ejs.renderFile)
const con = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'パスワードを設定',
database: 'testdb'
});
app.get('/', (req, res) => {
con.query('select * from title', function (err, results, fields) {
if (err) throw err
res.render('index.ejs', { content: results })
});
})
app.listen(3000, () => {
console.log('server start')
})
次にviewsディレクトリをプロジェクト配下に作成して、index.ejsを下記のコードで編集します。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top:50px;">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">id</th>
<th scope="col">title</th>
</tr>
</thead>
<tbody>
<% for(let i in content) { %>
<tr>
<% let obj = content[i]; %>
<th>
<%= obj.id %>
</th>
<th>
<%= obj.title %>
</th>
</tr>
<% } %>
</tbody>
</table>
</div>
</body>
</html>
起動します。
node app.js
ブラウザから http://プライベートIP:3000 にアクセスすると、titleテーブルのデータが表示されます

-
前の記事
vue.jsライブラリ「vue-swatches」の簡単な使い方 2020.02.10
-
次の記事
Vue.jsのライブラリvue-particlejsをインストールしてパーティクルアニメーションを実装する手順 2020.02.10
コメントを書く