Phần 14: NodeJS – Express Framework – NodeJS căn bản cho người mới bắt đầu

Table of Contents
Bài 14: NodeJS – Express Framework
– NodeJS căn bản cho người mới bắt đầu
Giới thiệu Express Framework
Express là 1 framework nhỏ và tiện ích để xây dựng những ứng dụng internet, cung cấp 1 lượng lớn của tính năng mạnh mẽ để phát triển những ứng dụng internet và cell. Nó cực dễ dàng để phát triển những ứng dụng nhanh dựa vào Node.js cho những ứng dụng Web. Dưới đây chính là các tính năng căn bản của Express framework.
Cho phép thiết lập các lớp trung gian để trả về các HTTP request.
Định nghĩ bảng routing có thể được dùng với những hành động khác nhau dựa vào phương thức HTTP và URL.
Cho phép trả về những trang HTML dựa vào các tham số truyền vào tới template.
Cài đặt Express Framework
Đầu tiên, cài đặt Express framework sử dụng npm như dưới đây:
$ npm set up categorical --save
Lệnh trên lưu phần cài đặt ở trong folder node_modules và tạo folder categorical bên trong folder đó. Dưới đây chính là những thành phần module quan trọng được cài đặt cùng categorical:
body-parser – Đây chính là 1 lớp trung gian node.js để xử lí JSON, dự liệu thô, textual content và mã hóa URL.
cookie-parser – Chuyển đổi header của Cookie và phân bố tới các req.cookies
multer – Đây chính là 1 thành phần trung gian trong node.js để xử lí phần multipart/form-data.
$ npm set up body-parser --save
$ npm set up cookie-parser --save
$ npm set up multer --save
Ví dụ ứng dụng Helloworld trong Node.js
Dưới đây chính là 1 ví dụ rất căn bản của Express minh họa cách bật Server và lắng nghe các kết nối trên cổng 3000. Ứng dụng này trả về Hello World! cho các requests tới trang chủ. Đối với những đường dẫn khác, nó sẽ trả về 1 404 Not Found.
Tạo server.js có nội dung sau:
var categorical = require('categorical');
var app = categorical();
app.get('/', operate (req, res) )
var server = app.hear(8081, operate ()
var host = server.tackle().tackle
var port = server.tackle().port
console.log("Example app listening at http://%s:%s", host, port)
)
Chạy server.js để xem kết quả.
$ node server.js
Bạn sẽ thấy kết quả hiện ra:
Ung dung Node.js dang lang nghe tai dia chi: http://0.0.0.0:8081
Mở http://127.0.0.1:8081/ trong bất kỳ trình duyệt nào và xem kết quả.
Đối tượng Request & Response trong Node.js
Ứng dụng Express sử dụng 1 hàm callback có các tham số là những đối tượng request và response.
app.get('/', operate (req, res) { // -- })
Bạn sẽ có thể xem thêm chi tiết về 2 đối tượng này sau đây:
- Đối tượng Request – Đối tượng này biểu diễn 1 HTTP request và có các thuộc tính cho các request như các chuỗi truy vấn, tham số, physique, HTTP header và các phần khác.
- Đối tượng Response – Đối tượng này biểu diễn HTTP response được ứng dụng Express gởi đi khi nó nhận về 1 HTTP request.
Bạn sẽ có thể in ra những đối tượng req và res để cung cấp 1 lượng lớn thông tin liên quan tới HTTP request và trả về các cookie, session, URL …
Định tuyến căn bản
Bên trên, bạn vừa theo dõi 1 ứng dụng căn bản mà Server HTTP request tới 1 trang chủ. Định tuyến liên quan tới cách xác định 1 ứng dụng trả về cho 1 Client Request tới 1 Endpoint chi tiết, đó là 1 link URI và trả về 1 phương thức HTTP request (GET, POST và những phương thức khác).
Dựa vào chương trình Hello World trên, mình sẽ phát triển thêm những tính năng bổ sung thêm để xử lý các HTTP request.
var categorical = require('categorical');
var app = categorical();
// This responds with "Hello World" on the homepage
app.get('/', operate (req, res) )
// This responds a POST request for the homepage
app.publish('/', operate (req, res) )
// This responds a DELETE request for the /del_user web page.
app.delete('/del_user', operate (req, res)
console.log("Got a DELETE request for /del_user");
res.ship('Hello DELETE');
)
// This responds a GET request for the /list_user web page.
app.get('/list_user', operate (req, res)
console.log("Got a GET request for /list_user");
res.ship('Page Listing');
)
// This responds a GET request for abcd, abxcd, ab123cd, and so forth
app.get('/ab*cd', operate(req, res)
console.log("Got a GET request for /ab*cd");
res.ship('Page Pattern Match');
)
var server = app.hear(8081, operate ()
var host = server.tackle().tackle
var port = server.tackle().port
console.log("Example app listening at http://%s:%s", host, port)
)
Lưu phần code trong server.js và chạy file này với lệnh sau:
$ node server.js
Kiểm tra kết quả:
Example app listening at http://0.0.0.0:8081
Hiện tại, bạn sẽ có thể thử các Request khác tại địa chỉ http://127.0.0.1:8081 để xem kết quả tạo do server.js. Dưới đây chính là vài màn hình hiển thị các response khác nhau với những URL khác nhau.
Màn hình kết quả cho http://127.0.0.1:8081/list_user
Màn hình kết quả cho http://127.0.0.1:8081/abcd
Màn hình kết quả cho http://127.0.0.1:8081/abcdefg
Đối với những File tĩnh
Express cung cấp những tiện ích lớp trung gian categorical.static nhằm phục vụ cho những file tĩnh như hình ảnh, CSS, Javascript, …
Về căn bản, bạn chỉ việc truyền tên folder nơi bạn giữ những file này, categorical.static sẽ sử dụng file đó 1 cách trực tiếp. Ví dụ, bạn cần giữ hình ảnh, CSS và Javascript trong folder public, bạn sẽ có thể làm như dưới đây:
app.use(categorical.static('public'));
Giả sử mình giữ một số hình ảnh trong folder con public/photos như dưới đây:
node_modules
server.js
public/
public/photos
public/photos/emblem.png
Chỉnh sửa ứng dụng “Hello Word” trên để thêm những tính năng bổ sung thêm để xử lý những file tĩnh:
var categorical = require('categorical');
var app = categorical();
app.use(categorical.static('public'));
app.get('/', operate (req, res) )
var server = app.hear(8081, operate ()
var host = server.tackle().tackle
var port = server.tackle().port
console.log("Example app listening at http://%s:%s", host, port)
)
Lưu phần code trong server.js và chạy file này với lệnh sau:
$ node server.js
Hiện tại mở trình duyệt và gõ địa chỉ http://127.0.0.1:8081/photos/emblem.png để xem kết quả.
Ví dụ phương thức GET
Dưới đây chính là 1 ví dụ đơn giản để truyền 2 giá trị sử dụng HTML FORM với phương thức GET. Mình sẽ sử dụng process_get trong server.js để xử lí phần enter.
<html>
<body>
<form motion = "http://127.0.0.1:8081/process_get" technique = "GET">
First Name: <input sort = "textual content" title = "first_name"> <br>
Last Name: <input sort = "textual content" title = "last_name">
<input sort = "submit" worth = "Submit">
</kind>
</physique>
</html>
Lưu đoạn mã trên trong index.htm và chỉnh sửa server.js như dưới đây.
var categorical = require('categorical');
var app = categorical();
app.use(categorical.static('public'));
app.get('/index.htm', operate (req, res) )
app.get('/process_get', operate (req, res) {
// Prepare output in JSON format
response =
first_name:req.question.first_name,
last_name:req.question.last_name
;
console.log(response);
res.finish(JSON.stringify(response));
})
var server = app.hear(8081, operate ()
var host = server.tackle().tackle
var port = server.tackle().port
console.log("Example app listening at http://%s:%s", host, port)
)
Mở trình duyệt và gõ địa chỉ http://127.0.0.1:8081/index.htm để xem kết quả:
{"first_name":"John","last_name":"Paul"}
Ví dụ phương thức POST
Dưới đây chính là ví dụ căn bản để truyền 2 giá trị sử dụng HTML kind do sử dụng phương thức POST. Mình sẽ sử dụng process_post trong server.js để xử lí phần enter này.
<html>
<body>
<form motion = "http://127.0.0.1:8081/process_post" technique = "POST">
First Name: <input sort = "textual content" title = "first_name"> <br>
Last Name: <input sort = "textual content" title = "last_name">
<input sort = "submit" worth = "Submit">
</kind>
</physique>
</html>
Lưu đoạn mã trên trong index.htm và chỉnh sửa server.js như dưới đây:
var categorical = require('categorical');
var app = categorical();
var bodyParser = require('body-parser');
// Create utility/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded( prolonged: false )
app.use(categorical.static('public'));
app.get('/index.htm', operate (req, res) )
app.publish('/process_post', urlencodedParser, operate (req, res) {
// Prepare output in JSON format
response =
first_name:req.physique.first_name,
last_name:req.physique.last_name
;
console.log(response);
res.finish(JSON.stringify(response));
})
var server = app.hear(8081, operate ()
var host = server.tackle().tackle
var port = server.tackle().port
console.log("Example app listening at http://%s:%s", host, port)
)
Mở trình duyệt và gõ địa chỉ http://127.0.0.1:8081/index.htm để xem kết quả:
{"first_name":"John","last_name":"Paul"}
Ví dụ File Upload
Dưới đây chính là HTML code để tạo 1 File Upload Form. Form này có những thuộc tính thiết lập tới phương thức POST và thuộc tính mã hóa để thiết lập multipart/form-data.
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to add: <br />
<form motion = "http://127.0.0.1:8081/file_upload" technique = "POST"
enctype = "multipart/form-data">
<input sort="file" title="file" measurement="50" />
<br />
<input sort = "submit" worth = "Upload File" />
</kind>
</physique>
</html>
Lưu đoạn mã trên trong index.htm và chỉnh sửa server.js như dưới đây:
var categorical = require('categorical');
var app = categorical();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(categorical.static('public'));
app.use(bodyParser.urlencoded( prolonged: false ));
app.use(multer({ dest: '/tmp/'}));
app.get('/index.htm', operate (req, res) )
app.publish('/file_upload', operate (req, res) {
console.log(req.recordsdata.file.title);
console.log(req.recordsdata.file.path);
console.log(req.recordsdata.file.sort);
var file = __dirname + "/" + req.recordsdata.file.title;
fs.learnFile( req.recordsdata.file.path, operate (err, information) {
fs.writeFile(file, information, operate (err) {
if( err ) {
console.log( err );
} else {
response = ;
}
console.log( response );
res.finish( JSON.stringify( response ) );
});
});
})
var server = app.hear(8081, operate ()
var host = server.tackle().tackle
var port = server.tackle().port
console.log("Example app listening at http://%s:%s", host, port)
)
Hiện tại bạn mở trình duyệt và gõ địa chỉ http://127.0.0.1:8081/index.htm để xem kết quả:
Ví dụ quản lý Cookie
Bạn sẽ có thể gởi các Cookie đến Node.js Server. Ví dụ sau đây minh họa cách in toàn bộ Cookie được gởi do Client.
var categorical = require('categorical')
var cookieParser = require('cookie-parser')
var app = categorical()
app.use(cookieParser())
app.get('/', operate(req, res) {
console.log("Cookies: ", req.cookies)
})
app.hear(8081