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

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

Cookie trong Expresss

Trong bài này chúng ta sẽ cùng nhau đi tìm hiểu về cookie trong Express. Khái niệm về cookie chắc hẳn đã khá quen thuộc với các bạn lập trình web nói chung và lập trình NodeJS nói riêng.

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.

Vậy Cookie trong NodeJS hoạt động ra sao thì chúng ta cùng tìm hiểu nhé.

1. Cookie trong NodeJS là gì?

Cookie là những tập tin một trang web gửi đến máy người dùng và được lưu lại thông qua trình duyệt khi người dùng truy cập trang web đó. Cookie được dùng để lưu trữ với rất nhiều mục đích như lưu phiên đăng nhập, hoạt động của người dùng khi truy cập trang web.

Cookie có nhiều loại khác nhau và phân chia theo từng mục đích sử dụng. Dưới đây là một số loại cookie để bạn tham khảo, ngoài ra còn nhiều loại cookie khác, bạn có thể tự mình tìm hiểu thêm :

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

  • Session Cookie: chỉ tồn tại tạm thời trong bộ nhớ của trình duyệt và sẽ bị trình duyệt tự xóa khi người dùng hết phiên đăng nhập, thông thường loại cookie này không có thời hạn.
  • Third-party cookie : thông thường cookie của trang web sẽ trùng với thanh địa chỉ của trình duyệt nhưng có một vài trường hợp sử dụng cookie bên thứ 3 có tên miền khác với url trang web
  • Secure cookie: một loại cookie HTTP có bộ thuộc tính secure giới hạn phạm vi của cookie đối với trình duyệt web.

2. Làm việc với cookie bằng middleware cookie-parse

Để sử dụng cookie trong express chúng ta cần phải cài thêm một vài middleware bên thứ 3 để hỗ trợ việc sử dụng cookie, nếu bạn chưa hiểu middleware là gì thì hãy xem lại bài tìm hiểu về middleware trong Express. Ở đây mình sử dụng middleware có tên cookie-parser, để cài đặt cookie-parser ta mở terminal lên và gõ dòng lệnh :

npm i --save cookie-parser

Thêm cookie-parser vào Express

Để có thể sử dụng cookie-parser chúng ta cần thêm middleware này vào trong dự án express của mình bằng cách khai báo sử dụng middleware cookieParse() :

//Sử dụng express
const express = require('express')
//Sử dụng module cookie-parse
const cookieParser = require('cookie-parser')
//Khởi tạo app express mới
const app = express()
//Khai báo sử dụng middleware cookieParse()
app.use(cookieParser())

Chúng ta có thể truyền vào method này 2 tham số :

cookieParser(secret, options)
  • secret: Có thể truyền vào đây một chuỗi hoặc một mảng dùng để signed cookie. Đây là trường không bắt buộc, nếu được truyền vào một chuỗi thì sẽ lấy chuỗi đó để sign cookie, một mảng thì tạm thời nó sẽ dùng để unsign cookie theo thứ tự của mảng.
  • options: truyền vào một object dùng để thêm vào cookie.parse

Tạo cookie mới

Để tạo một cookie mới ta sử dụng cú pháp:

res.cookie(name, value, [options])

chúng ta có 3 tham số có thể thêm vào :

  • name: tên của cookie cần thêm vào (bắt buộc)
  • value: giá trị của cookie (bắt buộc)
  • options: các tùy chỉnh khác

tham số options là một objects có thể có các thuộc tính như :

Thuộc tính Kiểu dữ liệu Miêu tả
domain string Domain của cookie, thường sẽ là domain của app
encode function Hàm dùng để encode cookie, mặc định là encodeURIComponent
expires date Thời điểm và cookie hết hạn, nếu không có giá trị hoặc giá trị bằng 0, nó sẽ tạo ra session cookie
httpOnly boolean Đánh dấu cookie chỉ có thể truy cập ở máy chủ web
maxAge number Thời gian hết hạn của cookie so với thời điểm đặt cookie, tính bằng mili giây
path string path của cookie, mặc định là '/'
secure boolean Đánh dấu cookie chỉ có thể được sử dụng ở giao thức https
signed boolean Đánh dấu cookie nên được signed
sameSite boolean hoặc string Giá trị sameSite của thuộc tính Set-Cookie

Làm ví dụ về Cookie

Chúng ta cùng tạo một ví dụ nhỏ về tạo cookie. Tạo file index.js có nội dung như sau:

var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
app.use(cookieParser())
app.get('/cookie', function(req, res){
     res.cookie('name', 'freetuts.net', { expires: new Date(Date.now() + 900000)});
     res.send('success') 
});
app.listen(3000)

mở terminal lên và chạy dòng lệnh:

node index

sau đó mở trình duyệt và truy cập địa chỉ localhost:3000/cookie, bạn có thể xem cookie của trang web trên trìn duyệt bằng cách mở Dev Tools -> Application -> Cookies

cookie trong nodejs png

Lấy giá trị của cookie

Chúng ta có thể lấy giá trị của cookie bằng cách sử dụng cú pháp :

req.cookie.[name]

Khi sử dụng middleware cookie-parser bạn sẽ nhận thêm 1 object trong biến request đó là cookie, tiếp nối ví dụ bên trên mình sẽ lấy giá trị của cookie vừa set.

Thêm một route vào file index.js trong ví dụ trước bằng cách sử dụng :

app.get('/getCookie', function(req, res){
    if (req.cookies.name)
        res.send(`Cookie name co gia tri la ${req.cookies.name}`)
   res.send('Khong the tim lay cookie co ten la name')
});

Route này có nhiệm vụ in ra giá trị của cookie name, lúc này file index.js có nội dung như sau :

var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
app.use(cookieParser())
app.get('/cookie', function(req, res){
     res.cookie('name', 'freetuts.net', { expires: new Date(Date.now() + 900000)});
     res.send('coookie set') 
});
app.get('/getCookie', function(req, res){
    if (req.cookies.name)
        res.send(`Cookie name co gia tri la ${req.cookies.name}`)
   res.send('Khong the tim lay cookie co ten la name')
});
app.listen(3000)

mở terminal và sử dụng lệnh

node index

Trên trình duyệt bạn gõ địa chỉ localhost:3000/getCookie để xem kết quả. Nếu bạn cookie có tên 'name' đã được lưu trữ trên trình duyệt rồi thì nó sẽ hiện ra giá trị của cookie,

Cookie name co gia tri la freetuts.net

ngược lại sẽ hiển thi :

Khong the tim lay cookie co ten la name

Xóa cookie hiện có

Để xóa cookie ta sẽ sử dụng phương thức clearCookie và truyền vào đó 2 tham số, tham số thứ nhất là tên cookie mà bạn muốn xóa, tham số thứ 2 là 1 object các tùy chỉnh.

res.clearCookie(cookieName, [options]);

Ví dụ như :

app.get('/deleteCookie', function(req, res){
   res.clearCookie('name');
   res.send('Da xoa cookie')
});

3. Nói một chút về Session trong Express

Đi song song với khái niệm cookie phải đề cập đến session, nếu như bạn đã từng lập trình PHP rồi thì chắc hẳn bạn có biết qua về session trong PHP. Thực chất session dựa trên cookie để hoạt động. Sau đây mình có một sơ đồ thể hiện cách mà session được tạo ra.

session trong expressjs jpg

Trước tiên, chương trình sẽ kiểm tra cookie có tổn tại hay không ? Tiếp theo chương trình sẽ kiểm tra nếu cookie chưa tồn tại, nó sẽ tạo ra một cookie để chứa giá trị của sessionID đồng thời cũng lưu trữ giá trị sessionID này trong database.

Trong bài này chúng ta đã cùng nhau đi tìm hiểu về cách xử lý cookie trong Express, đây là kiến thức rất cơ bản về nó nhưng cũng hết sức quan trọng trong quá trình làm việc với Express. Mong rằng bài viết sẽ giúp ích cho bạn.

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