LoginSignup
2
4

More than 5 years have passed since last update.

expressを使ってDBの値を取得・表示

Posted at

DB準備

とりあえず、一つテーブルを作成。

  • postsテーブル
    • title varchar(255)
    • content varchar(255)

以下のようにデータを入れておきます。

title content
title1 content1
title2 content2

アプリケーション実装

routes/index.js を以下のようにします。


var express = require('express');
var router = express.Router();

var posts = [];

/* db connect */
var mysql = require('mysql')
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'myuser',
  password : '******',
  database : 'my_db',
  insecureAuth : true
});

connection.connect()

// データベースからデータ取得
connection.query('SELECT * from posts;', function (err, rows, fields) {
  if (err) throw err

  posts = rows
})

connection.end()

/* GET home page. */
router.get('/', function(req, res, next) {
  // viewにデータを渡す
  res.render('index', { title: 'Express' , posts: posts});
});

module.exports = router;

viewテンプレートはとりあえず以下のような感じで。

{% extends 'layout.twig' %}

{% block body %}
  <h1>{{title}}</h1>
  <p>Welcome to {{title}}</p>
  <p>Hello World</p>

  {% for post in posts %}
    <p>{{ post.title }}</p>
    <p>{{ post.content }}</p>
  {% endfor %}
{% endblock %}

データ表示できましたー。

image.png

2
4
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
2
4