[BE201] Express & Sequelize part 2


Posted by yymarlerr on 2021-08-24

Node.js 和 MySQL 串接

前置作業

  • 安裝這個 library
    npm install mysql
  • 新增檔案 db.js,會得到在 demo_todo 裡面的資料:
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

connection.connect();

// 因為需要等一段時間才能拿到資料,所以用 callback function
connection.query('SELECT * FROM demo_todo', function (error, results, fields) {
  if (error) throw error;
  console.log(results);
});


connection.end();
  • db.js 的內容改為:
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'XXXX',
  password : 'XXXX',
  database : 'XXXX',
});

module.exports = connection

連接 sql

  • index.js 新增以下程式碼:
const db = require('./db')
app.listen(port, () => {
  db.connect()
  console.log(`hello world, listening on port ${port}`)
})

models

  • todo.js
const db = require('../db')

const todos = [
  'first todo', 'second todo', 'third todo'
]

const todoModel = {
  getAll: (cb) => { //用 callback function 拿資料
    db.query(
      'SELECT * FROM demo_todo', (error, results) => {
      if (error) return cb(error);
      cb(null, results)
    });
  },

  get: (id, cb) => {
    db.query(
      'SELECT * FROM demo_todo WHERE id = ?', [id], // 這邊用類似 prepare statement 的做法(可以搜尋 Escaping query values)
      (error, results) => { 
        if (error) return cb(error);
        cb(null, results)
    });
  }
}

module.exports = todoModel

controllers

  • todo.js
const todoModel = require('../models/todo')

const todoController = {
  getAll: (req, res) => {
    todoModel.getAll((error, results) => {
      if (error) return console.log(error)
      res.render('todos', { // 交給 view engine 去作
        todos: results
      })
    })
  },

  get: (req, res) => {
    const id = req.params.id
    todoModel.get(id, (error, results) => {
      if (error) return console.log(error)
      res.render('todo', {
        todo: results[0] // 因為即使只有一筆資料,也會是 array
      })
    })
  }
}

module.exports = todoController

views

  • todos.ejs
<h1>Todos</h1>

<ul>
<% for(let i = 0; i < todos.length; i++) { %>
  <li><%= todos[i].id %>: <%= todos[i].content %></li> <!--前面加等號,代表後面的東西要輸出-->
<% } %>
</ul>
  • todo.ejs
<h1>Todo</h1>

<h2><%= todo.content %></h2>









Related Posts

React newsletter

React newsletter

#1 擬訂計畫

#1 擬訂計畫

Airflow 動手玩:(七)Airflow Best Practices

Airflow 動手玩:(七)Airflow Best Practices


Comments