Nodejs mvc mysql

Trong các bài trước chúng ta đã tìm hiểu sơ lược về Express, trong phần này chúng ta sẽ sử dụng Express để xây dựng một ứng dụng ghi chú đơn giản, sử dụng mô hình MVC

Mô hình MVC trong Express

Bản thân Express không được xây dựng theo mô hình MVC, nhưng mô-đun

var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
4 được sử dụng để tạo dự án Express thì lại tạo cho chúng ta một ứng dụng gần giống với MVC bởi vì dự án này tồn tại ở thứ 2

  • Thư mục
    var notes = [];
    exports.update = exports.create = function(key, title, body) {
        notes[key] = { title: title, body: body };
    }
    
    exports.read = function(key) {
        return notes[key];
    }
    
    exports.destroy = function(key) {
        delete notes[key];
    }
    
    exports.keys = function() {
        return Object.keys(notes);
    }
    
    5 chứa các tệp mẫu (tệp có phần mở rộng là
    var notes = [];
    exports.update = exports.create = function(key, title, body) {
        notes[key] = { title: title, body: body };
    }
    
    exports.read = function(key) {
        return notes[key];
    }
    
    exports.destroy = function(key) {
        delete notes[key];
    }
    
    exports.keys = function() {
        return Object.keys(notes);
    }
    
    6), các tệp này được sử dụng để hiển thị dữ liệu, tức là tương tự với các phần Lượt xem trong MVC
  • Thư mục
    var notes = [];
    exports.update = exports.create = function(key, title, body) {
        notes[key] = { title: title, body: body };
    }
    
    exports.read = function(key) {
        return notes[key];
    }
    
    exports.destroy = function(key) {
        delete notes[key];
    }
    
    exports.keys = function() {
        return Object.keys(notes);
    }
    
    7 được sử dụng để chuyển hướng các URL đến các hàm xử lý tương ứng, tức là tương tự với Bộ điều khiển trong MVC

Do đó, để ứng dụng của chúng ta vận hành theo đúng mô hình MVC, thành phần còn thiếu là Model. Mô hình có chức năng lưu trữ dữ liệu, thay đổi/cập nhật dữ liệu, hỗ trợ truy vấn dữ liệu. Và dĩ nhiên là mô hình lưu trữ mã cũng nên được lưu trong một thư mục riêng biệt tách rời với

var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
5 và
var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
7

Tạo ứng dụng Ghi chú

Chúng ta sẽ xây dựng ứng dụng Notes (quản lý ghi chú) đơn giản

Đầu tiên chúng ta tạo dự án

C:\NodeJS>express --ejs notes
...

Sau đó cài đặt các module đi kèm

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...

Tạo mô hình

Trong thư mục gốc của dự án, chúng tôi tạo một thư mục có tên

...
var notes = require('./routes/notes');
...
0 nằm chung với các thư mục
var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
5,
var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
7… Trong thư mục
...
var notes = require('./routes/notes');
...
0, chúng tôi tạo một tệp có tên
...
var notes = require('./routes/notes');
...
4 với nội dung sau đây

var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}

Trong đoạn mã trên chúng ta tạo một mảng có tên

...
var notes = require('./routes/notes');
...
5 dùng để lưu trữ các ghi chú, mỗi ghi chú bao gồm
...
var notes = require('./routes/notes');
...
6(id),
...
var notes = require('./routes/notes');
...
7(tiêu đề) và
...
var notes = require('./routes/notes');
...
8 (nội dung). Trong phần này chúng tôi chỉ thực hiện lưu trữ trong bộ nhớ RAM để đơn giản, tức là làm mỗi lần tắt/khởi động máy chủ thì các ghi chú sẽ bị xóa, trong các phần sau chúng tôi sẽ sử dụng cơ sở dữ liệu để lưu trữ

Ở đoạn mã trên hàm

...
var notes = require('./routes/notes');
...
9 và hàm


    <%= title %>
    


    

<%= title %>

0 giống nhau vì ở đây chúng ta chưa sử dụng cơ sở dữ liệu, trong các phần sau khi sử dụng cơ sở dữ liệu thì các hàm này sẽ phải tách ra

Mỗi ghi chú sẽ được quản lý bằng

...
var notes = require('./routes/notes');
...
6 (key or id)

Tùy chỉnh trang chủ

Đầu tiên chúng tôi tạo một tệp có tên

...
var notes = require('./routes/notes');
...
4 trong thư mục
var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
7 rồi để đó, chúng tôi sẽ viết tệp này sau. Tiếp theo trong tệp


    <%= title %>
    


    

<%= title %>

4 chúng ta thêm các dòng sau vào cùng với các dòng


    <%= title %>
    


    

<%= title %>

5 ở đầu tệp

________số 8_______

Tiếp theo, cũng như trong các phần trước, chúng ta tách phần trang web ra thành các tệp



    <%= title %>
    


    

<%= title %>

6 để có thể sử dụng một cách linh hoạt khi cần

Trong thư mục

var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
5 chúng ta tạo các tệp


    <%= title %>
    


    

<%= title %>

6 như sau



    <%= title %>
    


    

<%= title %>

Chúng ta trong tiêu đề trang chủ và 2 đường link đến trang



    <%= title %>
    


    

<%= title %>

9 và trang


0 trang


1 sẽ được viết sau



Sau đó chỉnh sửa lại tệp



2 như sau

<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>

Trong tệp



3 chúng tôi sử dụng biến


4 chúng tôi sử dụng biến này để lấy
...
var notes = require('./routes/notes');
...
6 của từng ghi chú, sau đó hiển thị một đường liên kết đến
...
var notes = require('./routes/notes');
...
6 trong đó, biến
...
var notes = require('./routes/notes');
...
5 sẽ được gửi đến từ hàm


8, và đó sẽ là bất kỳ biến nào

var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;

Chúng ta thêm dòng



    <%= title %>
    


    

<%= title %>

5 đến mô-đun 
<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>
2 sau đó truyền vào lời gọi
<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>
3 để gửi tệp


2 có thể sử dụng
<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>
5

Đến đây chúng ta có thể chạy thử ứng dụng

C:\NodeJS\notes>npm start

Nodejs mvc mysql
Nodejs mvc mysql

Ở đây chúng ta chỉ thấy trang chủ và 2 đường dẫn trống không, vì chúng ta chưa tạo một ghi chú nào cả. Khi nhấn vào ADD Note thì sẽ có sai sót xảy ra vì chúng ta cũng chưa viết code cho trang này

Create note

Do đó bây giờ chúng ta sẽ thêm phần tạo ghi chú

Trong tệp



    <%= title %>
    


    

<%= title %>

4 chúng ta thêm dòng sau cùng với các dòng định tuyến khác

...
app.use('/noteadd', notes.add);
...

Trong tệp

<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>
7 chúng ta thêm đoạn mã sau

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
0

Đoạn mã trên rất đơn giản, chúng ta sử dụng hàm

<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>
3 để gọi tệp
<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>
9 và truyền tham số
var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
0 vào tệp này rồi trả về cho người dùng. Ở đây tham số
var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
1 cho biết chúng ta đang cập nhật hay tạo mới một ghi chú, nếu là cập nhật thì tham số
var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
2 sẽ là một đối tượng nào đó, còn tạo mới thì đối tượng này sẽ trống
var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
3 trong phần cập nhật

Tiếp theo trong thư mục

var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
4 chúng ta tạo tệp
<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>
9 với nội dung như sau

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
1

Như chúng ta đã biết, cả phần tạo và cập nhật ghi chú sử dụng chung một hàm, và sử dụng chung một mẫu là tệp

var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
6 Ở đây chúng ta tạo một biểu mẫu có các trường để nhập dữ liệu cho một ghi chú, nếu thao tác là

Biểu mẫu này sẽ gửi đến trang

var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
7 và biểu mẫu này sử dụng phương thức POST để gửi, do đó bây giờ chúng ta phải làm thêm trang này. Trong file


    <%= title %>
    


    

<%= title %>

4 chúng ta thêm dòng sau

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
2

Tiếp tục theo trong tệp

var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
9 chúng tôi thêm đoạn mã sau để xử lý các quy định của đường dẫn
C:\NodeJS\notes>npm start
0

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
3

Đoạn mã trên cũng rất đơn giản, chúng ta kiểm tra tham số

var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
1 là gì, nếu là tạo mới (create) thì chúng ta tạo một phần tử mới trong mảng ghi chú bằng phương thức
C:\NodeJS\notes>npm start
2 nếu là cập nhật thì chúng ta cập nhật
C:\NodeJS\notes>npm start
3

Sau đó chúng ta chuyển hướng trang web đến trang

C:\NodeJS\notes>npm start
4

Và bởi vì form truyền lên theo phương thức POST lên dữ liệu sẽ thuộc tính

C:\NodeJS\notes>npm start
5 được tạo từ mô-đun
C:\NodeJS\notes>npm start
6 Trong tệp


    <%= title %>
    


    

<%= title %>

4 Express tự động bổ sung mô-đun này cho chúng ta trong dòng
C:\NodeJS\notes>npm start
8

Bạn có thể chạy lại dự án và có thể nhấn nút THÊM Ghi chú để tạo ghi chú mới. Khi nhấn vào nút gửi, bạn sẽ nhận được một trang thông báo lỗi 404, đơn giản là vì chúng ta chưa làm trang

C:\NodeJS\notes>npm start
4

Nodejs mvc mysql
Nodejs mvc mysql

Tuy nhiên, nếu quay lại trang chủ thì chúng ta vẫn thấy ghi chú đã được thêm vào và đã hiển thị trên trang chủ

Nodejs mvc mysql
Nodejs mvc mysql

Xem ghi chú

Bây giờ chúng ta sẽ làm trang

...
app.use('/noteadd', notes.add);
...
0 để xem chi tiết một ghi chú

Trong file



    <%= title %>
    


    

<%= title %>

4 chúng ta thêm dòng sau

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
4

Trong file

var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
9 chúng ta thêm đoạn mã sau

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
5

Đoạn mã trên sẽ xử lý đường dẫn URL

...
app.use('/noteadd', notes.add);
...
3 ở đây chúng ta phải kiểm tra trước khi trả về dữ liệu cho trình duy nhất, bằng cách kiểm tra xem khóa có trống hay không, sau đó trong hàm
<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>
3 chúng ta cũng kiểm tra dữ liệu để xem
...
app.use('/noteadd', notes.add);
...
5 . Bởi vì người dùng có thể nhập đường dẫn bằng tay chứ không chỉ có sử dụng chuột để nhấp vào đường liên kết trên trang web

Cuối cùng chúng ta tạo một tệp có tên

...
app.use('/noteadd', notes.add);
...
6 trong thư mục
var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
5 với nội dung như sau

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
6

Đoạn mã trên sẽ chịu trách nhiệm hiển thị nội dung ghi chú. Ngoài ra còn hiển thị 2 đường liên kết đến trang

...
app.use('/noteadd', notes.add);
...
8 dùng để xóa ghi chú và
...
app.use('/noteadd', notes.add);
...
9 dùng để chỉnh sửa ghi chú

Nodejs mvc mysql
Nodejs mvc mysql

Tuy nhiên nếu click vào 2 đường link đó thì chúng ta sẽ được một trang báo lỗi 404, lý do cũng đơn giản là vì chúng ta chưa viết hàm Routing cho 2 đường dẫn này

Chỉnh sửa ghi chú

Trong file



    <%= title %>
    


    

<%= title %>

4 chúng ta thêm dòng sau

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
7

Trong file

var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
9 chúng ta thêm đoạn mã sau

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
8

Như bạn đã biết, cả 2 hàm tạo và chỉnh sửa đều sử dụng chung một mẫu là tệp

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
02 do đó ở đây chúng ta không cần phải tạo một tệp
var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
6 nào khác. Khác với chức năng tạo ghi chú, ở đây chúng ta nhận được một
...
var notes = require('./routes/notes');
...
6 của một ghi chú có sẵn, chúng ta sẽ truyền dữ liệu của ghi chú này vào các tham số được trả về. Đầu tiên chúng ta khai báo một biến
var express = require('express');
var router = express.Router();
var notes = require('../models/notes');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Notes', notes: notes });
});

module.exports = router;
2 có giá trị
C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
06 sau đó chúng ta tìm thấy các đối tượng ghi chú trong mảng
...
var notes = require('./routes/notes');
...
5 dựa theo
C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
08 nếu tìm thấy thì truyền vào hàm
C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
09 nếu không thì chúng ta truyền các tham số giống như khi tạo mới . Như thế sẽ phòng ngừa việc người dùng nhập đường dẫn bằng tay lên trình duyệt và đưa đường dẫn sai

Bây giờ bạn có thể thực hiện cập nhật ghi chú

Xóa ghi chú

Tương tự với các chức năng trên, đầu tiên chúng ta thêm dòng sau vào tệp

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
10

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
9

Tiếp theo trong tệp

<% include top %>
<%
    var keys = notes.keys();
    if(keys) {
        keys.forEach(function(key) {
            var note = notes.read(key);
            %>

<%= key %>: <%= note.title %>

<% }); } %> <% include bottom %>
7 chúng ta thêm đoạn mã sau

var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
0

Cũng tương tự như các chức năng khác, ở đây chúng ta kiểm tra xem dữ liệu gửi lên có hợp lệ hay không rồi trả về trong trang

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
12

Kế tiếp chúng ta tạo file

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
13 trong thư mục
var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
5 như sau

var notes = [];
exports.update = exports.create = function(key, title, body) {
    notes[key] = { title: title, body: body };
}

exports.read = function(key) {
    return notes[key];
}

exports.destroy = function(key) {
    delete notes[key];
}

exports.keys = function() {
    return Object.keys(notes);
}
1

Ở đây chúng tôi hiển thị một biểu mẫu cho người dùng xác nhận việc xóa tệp, biểu mẫu này sẽ gửi đến đường dẫn

C:\NodeJS>cd notes
C:\NodeJS\notes>npm install
...
15 với phương thức POST. Do đó bây giờ chúng ta phải xử lý đường dẫn này