peri hokiperihokiclarustologisticsrimashaop.comangelpaintingtools.co.invrjanaenergies.comgates of olympus perihoki jadi mesin uang paling gacortrik main baccarat perihoki ala pro bikin pemula jadi jutawanpantang pulang sebelum jackpot main dadu sicbo perihokipgsoft mahjong ways 2 muncul scatter merah tiap spin perihokicara menciptakan akun perihokigacor mahjong wins 3jackpot kembar mahjong wins 3 abc1131cara menang stabil rtp mahjong ways abc1131bu nurlina menang 197 juta mahjong ways 2mahasiswa cuan 421 juta karena pola mahjongpemilik warung menang 128 juta mahjong wins 3strategi bravy erika mahjong abc1131 terungkappemuda jambi taklukkan mahjong wins 3penjual jamu menang besar mahjong wins 5pemuda kampung raup 180 juta mahjong wayskisah inspiratif petani mahjong ways keberhasilanmahasiswa menang 92 juta mahjong waysmodal warung kopi bang ojak sukses mahjong waystanpa modal maxwin mahjong wins 3 strategibocoran mahjong ways spin kombinasicara bermain mahjong untuk meraih keberuntungankeajaiban mahjong kasir indomaret sukses beli tanahmeraup keuntungan maksimal di mahjong winsid rahasia scatter hitamid pola scatterid jackpot mahjong waysid spin mahjong winsid tips jitu mahjongrahasia kemenangan mahjong ways spin slow

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 282

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_cookie_params(): Cannot change session cookie parameters when headers already sent

Filename: Session/Session.php

Line Number: 294

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 304

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 314

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 315

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 316

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 317

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 375

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: drivers/Session_files_driver.php

Line Number: 108

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_save_handler(): Cannot change save handler when headers already sent

Filename: Session/Session.php

Line Number: 110

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_start(): Cannot start session when headers already sent

Filename: Session/Session.php

Line Number: 143

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

Middleware trong Express - Freetuts
EXPRESS FRAMEWORK
CÁC CHỦ ĐỀ
BÀI MỚI NHẤT
MỚI CẬP NHẬT

Middleware trong Express

Trong bài này mình sẽ cùng nhau đi tìm hiểu về middleware trong Express.JS, nhắc đến middleware chắc hẳn cũng đã rất quen thuộc với các bạn đã học lập trình Laravel.

test php

banquyen png
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

Middleware trong Express cũng tương tự như vậy, nó như một cầu nối liên kết cũng như kết dính các phần với nhau. Nào, bây giờ hãy bắt đầu tìm hiểu đến khái niệm nó là gì đã nhé.

1. Middleware trong Express là gì ?

Middleware là một phần rất quan trọng trong Express nó giúp chúng ta có thể lọc và ngăn chặn các request xấu trong quá trình chạy của ứng dụng. Middleware là các hàm khác nhau được gọi bởi [Route Express] trước khi các yêu cầu (request) hoàn tất.

Các hàm middleware có thê thực thi ở đầu, giữa, hoặc cuối vòng đời của một request. Trong stack các middleware function luôn được thêm vào theo thứ tự mà chúng ta mong muốn ngay ban đầu.

Bài viết này được đăng tại [free tuts .net]

middleware trong express jpg

Middleware thường sử dụng để thực hiện các tác vụ như: parseJSON, parseCookie, kiểm tra đăng nhập, thậm chí còn được sử dụng để viết các module một cách nhanh chóng.

2. Middleware Function trong Expresss

Các middlware function là các hàm có quyền truy cập vào các đối tượng như request(req), respone(res), next() trong chu kì của ứng dụng. next() là một hàm trong Route Express, khi được gọi hàm next() sẽ thực thi các middleware tiếp theo. Các middle function có thể thực hiện các chức năng như:

  • Thay đổi các đối tượng như request(req), respone(res)
  • Kết thúc vòng đời của một request.
  • Gọi các middleware sau trong stack

Chúng ta cùng nhau đi vào tìm hiểu các ví dụ thực tế bên dưới để có thể hình dung rõ hơn việc sử dụng middleware trong dự án thực tế nhé !

Khởi tạo một middleware function

Để khởi tạo middleware function chúng ta sử dụng :

//middleware function
var myLogger = function(req, res, next) {
  console.log("Middleware")
  next()
}
//Khai bao su dung middleware
app.use(myLogger)

Khi khởi tạo middleware bằng cách này thì bất cứ các request nào được gửi đến sẽ phải thông qua middleware, chúng ta hãy đi vào khởi tạo một app nhỏ trong đó sử dụng middleware để hiểu rõ hơn nhé !

Ví dụ về sử dụng middleware function

Chúng ta tạo 1 app nhỏ có chức năng kiểm tra đường dẫn và method của request gửi đến và dùng middleware để chặn request.

Tạo thư mục có tên middleware mở terminal và chạy dòng lệnh bên dưới để cài đặt express :

npm install --save express

Trong thư mục middleware tạo file có tên index.js có các phần sau :

Khai báo sử dụng express và khởi tạo app

const express = require('express')
const app = express()

Tạo middleware kiểm tra đường dẫn và method của request

//Middleware function kiểm tra request
var checkRequest = (req, res, next) => {
    console.log('Middleware chạy ở route có url ' + req.url + ' và method là ' + req.method )
    if (req.url === '/block') {
        res.send('Bạn không có quyền truy cập !')
    }else{
        next()
    }
}
//Khai báo sử dụng middleware
app.use(checkRequest)
//Khởi tạo route mới

TIếp theo chúng ta sẽ khởi tạo các route để cho người dùng truy cập

app.get('/', function (req, res) {
  res.send('Truy cập thành công !')
})
app.get('/home', function (req, res) {
  res.send('Truy cập thành công !')
})
app.get('/block', function (req, res) {
  res.send('Truy cập thành công !')
})
//Sử dụng port 3000 
app.listen(3000)

Cuối cùng file index.js sẽ có nội dung đầy đủ như sau :

const express = require('express')
const app = express()
//Middleware function kiểm tra request
var checkRequest = (req, res, next) => {
    console.log('Middleware chạy ở route có url ' + req.url + ' và method là ' + req.method )
    if (req.url === '/block') {
        res.send('Bạn không có quyền truy cập !')
    }else{
        next()
    }
}
//Khai báo sử dụng middleware
app.use(checkRequest)
//Khởi tạo route mới

app.get('/', function (req, res) {
  res.send('Truy cập thành công / !')
})
app.get('/home', function (req, res) {
  res.send('Truy cập thành công home!')
})
app.get('/block', function (req, res) {
  res.send('Truy cập thành công block !')
})

//Sử dụng port 3000 
app.listen(3000)

Mở terminal và sử dụng dòng lệnh sau để chạy app

node index.js

Khi truy cập đường dẫn localhost:3000/block thì bạn sẽ nhận được thông báo "bạn không có quyền truy cập" mặc dù trong route bạn đã khai báo response về giá trị 'Truy cập thành công block !'. Lý do bởi khi middleware được chạy ở ở đầu vòng đời của request nên nó đã kiểm tra giá trị và response lại trước khi route response. Bạn có thể chạy và xem kết quả để hiểu rõ hơn nhé !

middleware trong nodejs png

3. Các loại middleware trong Express

Chúng ta có thể chia middleware ra nhiều kiểu khác nhau và sử dụng nó vào từng trường hợp cụ thể của nó. Dưới đây là một số các kiểu middleware được express cung cấp cho chúng ta.

Application-level middleware

Chúng ta có thể khai báo middleware bằng cách thêm nó vào các hàm như app.use(), app.GET(), app.POST(), app.PUT(),..

Khi middleware được khai bái bằng app.use() như trong ví dụ trên tất cả các các request đều phải đi qua middleware function :

var app = express()

app.use(function (req, res, next) {
  console.log('Receive all request')
  next()
})

Khi middleware được khai báo bằng cách sử dụng các route thì nó chỉ các request trong route đó mới thông qua middleware function :

app.get('/user/:id', function (req, res, next) {
  console.log('ID:', req.params.id)
  next()
}, function (req, res, next) {
  res.send('User Info')
})

Router-level middleware

Chúng ta cũng có thể sử dụng middleware trong phạm vi Router, cách thức hoạt động giống như trong Application-level middleware nhưng nó phu thuộc vào biến express.Router()

var router = express.Router()

Ví dụ bên dưới thể hiện rất rõ điều đó :

var app = express()
var router = express.Router()

router.use(function (req, res, next) {
  console.log('middleware run')
  next()
})

router.get('/', function (req, res) {
  res.send('hello, user!')
})

Error-handling middleware

Thay vì truyền 3 tham số vào hàm middleware như các ví dụ ở trên, bạn nên bắt lỗi middleware bằng cách truyền vào nó 4 tham số, tham số đầu tiền sẽ là biến nhận kết quả lỗi của middleware.

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

Third-party middleware

Bạn cũng có thể sử dụng các middleware bên thứ 3 để có thể mở rộng dự án của mình một cách dễ dàng hơn, sử dụng công cụ npm để cài đặt và đưa nó vào trong dự án của bạn. Ví dụ sau mình sẽ cài 1 middleware hỗ trợ có tên là cookie-parser , nó cho phép chúng ta làm việc với cookie dễ dàng hơn trong Express. Mở terminal và gõ dòng lênh sau :

npm install --save cookie-parse

Thêm middleware này vào trong dự án của bạn

var express = require('express')
var app = express()
var cookieParser = require('cookie-parser')

// load the cookie-parsing middleware
app.use(cookieParser())

Trên đây là những kiến thức cơ bản cũng như đầy đủ về middleware trong Express, rất mong những phần mình vừa chia sẻ sẽ giúp ích bạn trong quá trình lập trình với NodeJS nói chung và sử dụng Express Framework nói riêng :))

Cùng chuyên mục:

Cách gửi mail trong NodeJS có file đính kèm

Cách gửi mail trong NodeJS có file đính kèm

Crawl dữ liệu website bằng NodeJS cơ bản

Crawl dữ liệu website bằng NodeJS cơ bản

CORS là gì ? Xử lý CORS trong NodeJS

CORS là gì ? Xử lý CORS trong NodeJS

Chắc hẳn trong quá trình xử lý các request tới server thì một vài trường…

Xử lý form trong Express

Xử lý form trong Express

Xây dựng URL trong Express

Xây dựng URL trong Express

Trong bài viết này chúng ta sẽ cùng nhau đi tìm hiểu về cách xây…

Populate trong Mongoose

Populate trong Mongoose

Error Handling & Debugging trong Socket.io

Error Handling & Debugging trong Socket.io

Namespaces & Rooms trong Socket.io

Namespaces & Rooms trong Socket.io

Middleware trong Mongoose

Middleware trong Mongoose

Create / Read / Update / Delete trong Mongoose

Create / Read / Update / Delete trong Mongoose

Validation trong Mongoose

Validation trong Mongoose

Subdocuments trong Mongooose

Subdocuments trong Mongooose

Documents trong Mongoose

Documents trong Mongoose

Trong bài viết này chúng ta sẽ tìm hiểu về documents trong Mongoose

Models trong Mongoose

Models trong Mongoose

SchemaTypes trong Mongoose

SchemaTypes trong Mongoose

Schemas trong Mongoose

Schemas trong Mongoose

Mongoose trong NodeJS

Mongoose trong NodeJS

Làm việc với Table MySQL sử dụng Nodejs

Làm việc với Table MySQL sử dụng Nodejs

Kết nối với MongoDB trong NodeJS

Kết nối với MongoDB trong NodeJS

Giới thiệu MongoDB trong NodeJS

Giới thiệu MongoDB trong NodeJS

Top