Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Lập trình MVC trong NodeJS hướng dẫn bạn cách thức phát triển website trong NodeJS với mô hình lập trình MVC.

Đôi điều về web Framework Express

Express là module rất phổ biến trong thế giới NodeJS, nó  giúp web dev tạo nên các chức năng cơ bản cho project mà không phải thực hiện nhiều việc thủ công.  Website của express là http://expressjs.com  

Bạn nên cài đặt express ở chế độ global, để sử dụng nó cho việc tạo project ở máy local nhanh hơn. Ngoài express, module express-generator cũng hết sức cần thiết cài vào, vì nó giúp bạn phát sinh các file và folder cần dùng lúc bắt đầu project. Thực hiện cài đặt như sau:

  1. Mở command line
  2. Gõ  lệnh npm install -g expressnpm install -g express
  3. Tiếp theo gõ lệnh  npm -g install express-generatornpm -g install express-generator

1. Tạo project với express

Vào command line và chuyển đến folder chứa project rồi chạy lệnh:

express --ejs LabTest

Bạn sẽ thấy folder LabTest xuất hiện các folder và file trong đó

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql
Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Trong folder project có file app.js , đây là file chính, giống file main trong C++.  Express còn tạo 2 module routes/index và routes/users để xử lý các request HTTP.  Hàm app.set() thường thấy trong code dùng để gán thông số cho project và các module. .app.js , đây là file chính, giống file main trong C++.  Express còn tạo 2 module routes/index và routes/users để xử lý các request HTTP.  Hàm app.set() thường thấy trong code dùng để gán thông số cho project và các module. .

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Như hình trên, bạn thấy các thư viện cần thiết đã được nhúng, đã set sẵn view engine cũng thiết lặp, folder views và folder public đã chỉ định. 3 controller indexRouter và usersRouter cũng đã được khai báo và chỉ định.views và folder public đã chỉ định. 3 controller indexRouter và usersRouter cũng đã được khai báo và chỉ định.

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

File www trong folder bin đã cũng đã listen sẵn ở port 3000 cho bạn.www trong folder bin đã cũng đã listen sẵn ở port 3000 cho bạn.

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

File package.json đã chỉ định start mặc định file bin/wwwpackage.json đã chỉ định start mặc định file bin/www

2. Cài module cho project

Chuyển vào folder project rồi chạy lệnh : npm install để cài thêm các chức năng cơ bản khác nhé.npm install để cài thêm các chức năng cơ bản khác nhé.

3. Chạy project

Giờ thì đã có cấu trúc folder cùng các module cơ bạn, chạy project thôi. Chạy 1 trong 2 lệnh npm start hoặc node bin/wwwnpm start hoặc node bin/www

Test: http://localhost:3000

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Mô hình MVC

MVC là mô hình thường được dùng hiện nay để phát triển các webite. Vì MVC giúp tổ chức tách bạch giữa các thành phần quan trọng trong dự án:  điều khiển (controller), xử lý dữ liệu (model) và hiển thị dữ liệu (view).

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql
Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Controller trong mvc

Controller được tạo ra để thực thi các yêu cầu từ user,  controller thực hiện tiếp nhận tham số, gọi các hàm trong model, nạp các view cần thiết… Trong NodeJS , routes đóng vai trò như controller.

Model trong mvc

Model dùng để cung cấp dữ liệu, thực hiện kết nối, trích lọc, chèn, chỉnh sửa dữ liệu trong database, tương tác với file system, network.

View trong mvc

Mỗi view là một trang web hiển thị dữ liệu gì đó. Dữ liệu mà view hiển thị do controller cung cấp (controller lấy từ model để đưa cho view).

Việc tách riêntg vai trò của Controler, Model và View giúp cho team phân định rõ ràng các công việc xử lý nghiệp vụ, xử lý dữ liệu và trình bày dữ liệu. Do vậy việc cập nhật chỉnh sửa một thành phần không làm ảnh hưởng đến các thành phần khác.

Mô hình MVC trong Express

Lập trình MVC trong NodeJS tức bạn sẽ tạo nên các chức năng cho website quy ước của MVC. Theo đó, các việc xử lý request, hiển thị dữ liệu , xử lý dữ liệu phải tách bạch ra theo quy định. tức bạn sẽ tạo nên các chức năng cho website quy ước của MVC. Theo đó, các việc xử lý request, hiển thị dữ liệu , xử lý dữ liệu phải tách bạch ra theo quy định.

Module express-generator giúp bạn tạo project đã gần giống với tổ chức MVC, như folder views chứa các file view để hiện dữ liệu, folder routes dùng để xử lý các đường path chính là thành phần controller trong MVC. Bạn cần tạo thêm thành phần model nữa để xử lý dữ liệu. views chứa các file view để hiện dữ liệu, folder routes dùng để xử lý các đường path chính là thành phần controller trong MVC. Bạn cần tạo thêm thành phần model nữa để xử lý dữ liệu.

Để hiểu rõ lập trình MVC trong NodeJS là thế nào, chúng ta sẽ thực hiện một ví dụ lớn nhé. Sau đây là phần hướng dẫn tạo controller, model, view để quản trị dữ liệu trong table có tên là loai (sách). lập trình MVC trong NodeJS là thế nào, chúng ta sẽ thực hiện một ví dụ lớn nhé. Sau đây là phần hướng dẫn tạo controller, model, view để quản trị dữ liệu trong table có tên là loai (sách).

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Tạo controller trong nodejs

– Tạo file routes/loai.js

– Định nghĩa các route cho các action sẽ thực hiện list record, addnew, store, edit, update, delete

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

router.get('/', function(req, res, next) {
    res.send('Danh sách loại sách');  
});
router.get('/addnew', function(req, res, next) {
    res.send('Form thêm loại sách'); 
});
router.post('/store', function(req, res, next) {
    //nhận dữ liệu từ addnew để thêm record vào db
});
router.get('/edit/:id', function(req, res, next) {
  var id = req.params.id;
  res.send('Form chỉnh loại sách' + id);
});
router.post('/update', function(req, res, next) {
    //nhận dữ liệu từ edit để cập nhật vào db
});
router.get('/delete/:id', function(req, res) {
  var id = req.params.id;
  res.send('Xóa loai');
});

module.exports = router;

– Mở app.js và thêm code khai báo route cho controller

var loaiRouter = require('./routes/loai');
app.use('/loai', loaiRouter);

Test các route, nếu thấy các chữ trong controller hiện ra là đúng.

http://localhost:3000/loai/
http://localhost:3000/loai/addnew
http://localhost:3000/loai/edit/1
http://localhost:3000/loai/delete/1
Tới đây đã tạo controller xong , bạn biết cách tạo controller ,tạo đường dẫn cho các chức năng rồi đó.
Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Tới đây đã tạo controller xong , bạn biết cách tạo controller ,tạo đường dẫn cho các chức năng rồi đó.

Tạo model

Thành phần model giúp tương tác với các hệ thống chứa dữ liệu.

– Mở command line, chuyển vào folder project– Tạo folder tên models để chứa các model sẽ tạo – Cài module mysql– Tạo file models/database.js và code:
– Tạo folder tên models để chứa các model sẽ tạo
– Cài module mysql
– Tạo file models/database.js và code:

//Database trả về kết nối với cơ sở dữ liệu
var mysql = require('mysql');
var db = mysql.createConnection({
   host: 'localhost', user: 'root', password: '', 
   database: 'labnodejs'
}); 
db.connect(() => console.log('Da ket noi database !'));
module.exports = db; 
//lệnh exports để xuất (public) ra, cho ngoài module dùng được db

Nhúng model vào controller:

-Ở đầu controller loai, chèn model vào

var db=require('../models/database');

Chức năng hiện danh sách record

– Code trong route / của controller loai/ của controller loai

router.get('/', function(req, res, next) {    
    let sql = `SELECT * FROM loai`;
    db.query(sql, function(err, data) {      
        res.render("loai_list",{list:data});    
    }); 
});

– Tạo view:

Tạo file views/loai_list.ejs để hiển thị các record lấy được từ dbviews/loai_list.ejs để hiển thị các record lấy được từ db



<% for (let c of list ) { %> <% } %>
id Tên loại Thứ tự Ẩn hiện
<%= c.id %> <%= c.tenLoai %> <%= c.thuTu %> <%= c.anHien==1 ? "Đang hiện" : "Đang ẩn"%>

– Test: http://localhost:3000/loai/

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Chức năng hiện form thêm mới

– Code trong route addnew của controller loaiaddnew của controller loai

router.get('/addnew', function(req, res, next) {
    //res.send('Form thêm loại sách'); 
    res.render("loai_addnew");
});

– Tạo view:

Tạo file views/loai_addnew.ejs, trong view có form với method là post và trỏ lên action storeloai_addnew.ejs, trong view có form với method là post và trỏ lên action store



Hiện     Ẩn

– Test: http://localhost:3000/loai/addnew

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Chức năng lưu form vào database

– Code trong route store của controller loaistore của controller loai

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

router.get('/', function(req, res, next) {
    res.send('Danh sách loại sách');  
});
router.get('/addnew', function(req, res, next) {
    res.send('Form thêm loại sách'); 
});
router.post('/store', function(req, res, next) {
    //nhận dữ liệu từ addnew để thêm record vào db
});
router.get('/edit/:id', function(req, res, next) {
  var id = req.params.id;
  res.send('Form chỉnh loại sách' + id);
});
router.post('/update', function(req, res, next) {
    //nhận dữ liệu từ edit để cập nhật vào db
});
router.get('/delete/:id', function(req, res) {
  var id = req.params.id;
  res.send('Xóa loai');
});

module.exports = router;
0

Test lại từ form, khi submit sẽ thấy có dữ liệu mới

Chức năng hiện form edit 1 record

– Code trong route edit của controller loaiedit của controller loai

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

router.get('/', function(req, res, next) {
    res.send('Danh sách loại sách');  
});
router.get('/addnew', function(req, res, next) {
    res.send('Form thêm loại sách'); 
});
router.post('/store', function(req, res, next) {
    //nhận dữ liệu từ addnew để thêm record vào db
});
router.get('/edit/:id', function(req, res, next) {
  var id = req.params.id;
  res.send('Form chỉnh loại sách' + id);
});
router.post('/update', function(req, res, next) {
    //nhận dữ liệu từ edit để cập nhật vào db
});
router.get('/delete/:id', function(req, res) {
  var id = req.params.id;
  res.send('Xóa loai');
});

module.exports = router;
1

– Tạo view:

a. Save as file loai_addnew. thành loai_edit.ejsb. Chỉnh thuộc tính action của form từ store thành updatec. Hiện thông tin record trong form. Tham khảo hình sauloai_addnew. thành loai_edit.ejs
b. Chỉnh thuộc tính action của form từ store thành update
c. Hiện thông tin record trong form. Tham khảo hình sau

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

d. Thêm code sau vào trong form để giữ id của loại cần cập nhật, chút nữa sẽ dùng khi lưu database

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

router.get('/', function(req, res, next) {
    res.send('Danh sách loại sách');  
});
router.get('/addnew', function(req, res, next) {
    res.send('Form thêm loại sách'); 
});
router.post('/store', function(req, res, next) {
    //nhận dữ liệu từ addnew để thêm record vào db
});
router.get('/edit/:id', function(req, res, next) {
  var id = req.params.id;
  res.send('Form chỉnh loại sách' + id);
});
router.post('/update', function(req, res, next) {
    //nhận dữ liệu từ edit để cập nhật vào db
});
router.get('/delete/:id', function(req, res) {
  var id = req.params.id;
  res.send('Xóa loai');
});

module.exports = router;
2

e. Test: http://localhost:3000/loai/edit/1

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql

Code cập nhật record vào database

– Code trong route update của controller loai: update của controller loai:

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

router.get('/', function(req, res, next) {
    res.send('Danh sách loại sách');  
});
router.get('/addnew', function(req, res, next) {
    res.send('Form thêm loại sách'); 
});
router.post('/store', function(req, res, next) {
    //nhận dữ liệu từ addnew để thêm record vào db
});
router.get('/edit/:id', function(req, res, next) {
  var id = req.params.id;
  res.send('Form chỉnh loại sách' + id);
});
router.post('/update', function(req, res, next) {
    //nhận dữ liệu từ edit để cập nhật vào db
});
router.get('/delete/:id', function(req, res) {
  var id = req.params.id;
  res.send('Xóa loai');
});

module.exports = router;
3

– Test: nhập giá trị mới trong form và lưu, sẽ thấy tác dụng

Chức năng xóa 1 record trong database

– Code trong route delete của controler loai

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

router.get('/', function(req, res, next) {
    res.send('Danh sách loại sách');  
});
router.get('/addnew', function(req, res, next) {
    res.send('Form thêm loại sách'); 
});
router.post('/store', function(req, res, next) {
    //nhận dữ liệu từ addnew để thêm record vào db
});
router.get('/edit/:id', function(req, res, next) {
  var id = req.params.id;
  res.send('Form chỉnh loại sách' + id);
});
router.post('/update', function(req, res, next) {
    //nhận dữ liệu từ edit để cập nhật vào db
});
router.get('/delete/:id', function(req, res) {
  var id = req.params.id;
  res.send('Xóa loai');
});

module.exports = router;
4

– Test

Lập trình MVC trong NodeJS giúp bạn thực hiện công việc theo khuôn mẫu, nhờ đó làm nhanh hơn, sự tách bạch các thành phần giúp dễ dò lỗi, dễ chia việc trong team…

À, bài cần phải có kiến thức kết nối database trong NodeJS, bạn cần đọc bài Làm việc với mysql trong NodeJS trước đã nhé


Bài tập: thực hiện luyện tập mvc tương tự như bài học nhưng với table sach như sau:sach như sau:

Hướng dẫn mvc nodejs mysql - mvc nodejs mysql