1. Trang chủ
  2. » Thể loại khác

express framework trong nodejs

9 236 3

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Express Framework Node.js Giới thiệu Express Framework Express framework nhỏ tiện ích để xây dựng ứng dụng web, cung cấp lượng lớn tính mạnh mẽ để phát triển ứng dụng web mobile Nó dễ dàng để phát triển ứng dụng nhanh dựa Node.js cho ứng dụng Web Dưới tính Express framework • Cho phép thiết lập lớp trung gian để trả HTTP request • Định nghĩ bảng routing sử dụng với hành động khác dựa phương thức HTTP URL • Cho phép trả trang HTML dựa vào tham số truyền vào đến template Cài đặt Express Framework Đầu tiên, cài đặt Express framework sử dụng npm sau: $ npm install express save Lệnh lưu phần cài đặt thư mục node_modules tạo thư mục express bên thư mục Dưới thành phần module quan trọng cài đặt với express: • body-parser - Đây lớp trung gian node.js để xử lí JSON, dự liệu thơ, text mã hóa URL • cookie-parser - Chuyển đổi header Cookie phân bố đến req.cookies • multer - Đây thành phần trung gian node.js để xử lí phần multipart/form-data $ npm install body-parser save $ npm install cookie-parser save $ npm install multer save http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Ví dụ ứng dụng Helloworld Node.js Dưới ví dụ Express minh họa cách bật Server lắng nghe kết nối cổng 3000 Ứng dụng trả Hello World! cho requests đến trang chủ Đối với đường dẫn khác, trả 404 Not Found Tạo server.js có nội dung sau: var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s", host, port) }) Chạy server.js để xem kết $ node server.js Bạn thấy kết ra: Ung dung Node.js dang lang nghe tai dia chi: http://0.0.0.0:8081 Mở http://127.0.0.1:8081/ trình duyệt xem kết http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Đối tượng Request & Response Node.js Ứng dụng Express sử dụng hàm callback có tham số đối tượng request vàresponse app.get('/', function (req, res) { // }) Bạn tham khảo chi tiết đối tượng đây: • Đối tượng Request - Đối tượng biểu diễn HTTP request có thuộc tính cho request chuỗi truy vấn, tham số, body, HTTP header phần khác • Đối tượng Response - Đối tượng biểu diễn HTTP response ứng dụng Express gửi nhận HTTP request Bạn in đối tượng req res để cung cấp lượng lớn thông tin liên quan đến HTTP request trả cookie, session, URL … http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Định tuyến Ở trên, bạn vừa theo dõi ứng dụng mà Server HTTP request đến trang chủ Định tuyến liên quan đến cách xác định ứng dụng trả cho Client Request đến Endpoint cụ thể, đường dẫn URI trả phương thức HTTP request (GET, POST phương thức khác) Dựa vào chương trình Hello World trên, phát triển thêm số chức bổ sung để xử lý HTTP request var express = require('express'); var app = express(); // Phuong thuc get() phan hoi mot GET Request ve Homepage app.get('/', function (req, res) { console.log("Nhan mot GET Request ve Homepage"); res.send('Hello GET'); }) // Phuong thuc post() phan hoi mot POST Request ve Homepage app.post('/', function (req, res) { console.log("Nhan mot POST Request ve Homepage"); res.send('Hello POST'); }) // Phuong thuc delete() phan hoi mot DELETE Request ve /del_user page app.delete('/del_user', function (req, res) { console.log("Nhan mot DELETE Request ve /del_user"); res.send('Hello DELETE'); }) // Phuong thuc phan hoi mot GET Request ve /list_user page app.get('/list_user', function (req, res) { console.log("Nhan mot GET Request ve /list_user"); res.send('Page Listing'); }) // Phuong thuc phan hoi mot GET Request ve abcd, abxcd, ab123cd, app.get('/ab*cd', function(req, res) { console.log("Nhan mot GET request ve /ab*cd"); res.send('Page Pattern Match'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s", host, port) }) Lưu phần code server.js chạy file với lệnh sau: $ node server.js Kiểm tra kết quả: Ung dung Node.js dang lang nghe tai dia chi: http://0.0.0.0:8081 Bây giờ, bạn thử Request khác địa http://127.0.0.1:8081 để xem kết tạo server.js Dưới vài hình hiển thị response khác với URL khác Màn hình kết cho http://127.0.0.1:8081/list_user http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Màn hình kết cho http://127.0.0.1:8081/abcd http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Màn hình kết cho http://127.0.0.1:8081/abcdefg Đối với File tĩnh Express cung cấp tiện ích lớp trung gian express.static để phục vụ cho file tĩnh hình ảnh, CSS, Javascript, Về bản, bạn cần truyền tên thư mục nơi bạn giữ file này, express.static sử dụng file cách trực tiếp Ví dụ, bạn muốn giữ hình ảnh, CSS Javascript thư mục public, bạn làm sau: app.use(express.static('public')); Giả sử giữ vài hình ảnh thư mục public/images sau: node_modules server.js public/ public/images public/images/logo.png Sửa đổi ứng dụng "Hello Word" để thêm số tính bổ sung để xử lý file tĩnh: var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/', function (req, res) { http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     res.send('Hello World'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s", host, port) }) Lưu phần code server.js chạy file với lệnh sau: $ node server.js Bây mở trình duyệt gõ địa http://127.0.0.1:8081/images/logo.png để xem kết Ví dụ phương thức GET Dưới ví dụ đơn giản để truyền giá trị sử dụng HTML FORM với phương thức GET Mình sử dụng process_get server.js để xử lí phần input First Name: Last Name: Lưu đoạn code index.htm sửa đổi server.js sau var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/index.htm', function (req, res) { res.sendFile( dirname + "/" + "index.htm" ); }) app.get('/process_get', function (req, res) { // Chuan bi output dinh dang JSON response = { first_name:req.query.first_name, last_name:req.query.last_name }; console.log(response); res.end(JSON.stringify(response)); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s", host, port) }) Mở trình duyệt gõ địa http://127.0.0.1:8081/index.htm để xem kết quả: First  Name:   Last  Name:     Bây giờ, bạn nhập First Name Last Name, nhấn nút Submit xem kết quả: http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     {"first_name":"Hoang","last_name":"Nguyen Manh"} Ví dụ phương thức POST Dưới ví dụ để truyền giá trị sử dụng HTML form sử dụng phương thức POST Mình sử dụng process_post server.js để xử lí phần input First Name: Last Name: Lưu đoạn code index.htm sửa đổi server.js sau: var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // Tao mot parser co dang application/x-www-formurlencoded var urlencodedParser = bodyParser.urlencoded({ extended: false }) app.use(express.static('public')); app.get('/index.htm', function (req, res) { res.sendFile( dirname + "/" + "index.htm" ); }) app.post('/process_post', urlencodedParser, function (req, res) { // Chuan bi output dinh dang JSON response = { first_name:req.body.first_name, last_name:req.body.last_name }; console.log(response); res.end(JSON.stringify(response)); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s", host, port) }) Mở trình duyệt gõ địa http://127.0.0.1:8081/index.htm để xem kết quả: First  Name:   Last  Name:     Bây giờ, bạn nhập First Name Last Name, nhấn nút Submit xem kết quả: {"first_name":"Hoang","last_name":"Nguyen Manh"} Ví dụ File Upload Dưới HTML code để tạo File Upload Form Form có thuộc tính thiết lập đến phương thức POST thuộc tính mã hóa để thiết lập multipart/form-data http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     File Uploading Form File Upload: Select a file to upload: Lưu đoạn code index.htm sửa đổi server.js sau: var express = require('express'); var app = express(); var fs = require("fs"); var bodyParser = require('body-parser'); var multer = require('multer'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(multer({ dest: '/tmp/'})); app.get('/index.htm', function (req, res) { res.sendFile( dirname + "/" + "index.htm" ); }) app.post('/file_upload', function (req, res) { console.log(req.files.file.name); console.log(req.files.file.path); console.log(req.files.file.type); var file = dirname + "/" + req.files.file.name; fs.readFile( req.files.file.path, function (err, data) { fs.writeFile(file, data, function (err) { if( err ){ console.log( err ); }else{ response = { message:'File duoc upload cong!', filename:req.files.file.name }; } console.log( response ); res.end( JSON.stringify( response ) ); }); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s", host, port) }) Bây bạn mở trình duyệt gõ địa http://127.0.0.1:8081/index.htm để xem kết quả: File Upload: Chọn File để Upload: Ghi chú: Đây ví dụ khơng làm việc Ví dụ quản lý Cookie Bạn gửi Cookie tới Node.js Server Ví dụ minh họa cách in tất Cookie gửi Client var express = require('express') var cookieParser = require('cookieparser') var app = express() app.use(cookieParser()) app.get('/', function(req, res) { console.log("Cookies: ", req.cookies) }) app.listen(8081)   http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   ... dụng "Hello Word" để thêm số tính bổ sung để xử lý file tĩnh: var express = require( 'express' ); var app = express( ); app.use (express. static('public')); app.get('/', function (req, res) { http://vietjack.com/... Lưu đoạn code index.htm sửa đổi server.js sau var express = require( 'express' ); var app = express( ); app.use (express. static('public')); app.get('/index.htm', function (req, res)... server.js sau: var express = require( 'express' ); var app = express( ); var fs = require("fs"); var bodyParser = require('body-parser'); var multer = require('multer'); app.use (express. static('public'));

Ngày đăng: 02/12/2017, 12:22

Xem thêm:

TỪ KHÓA LIÊN QUAN