Ở bài trước MiniBlog đã có layout chung, nhưng mới chỉ hiển thị dữ liệu có sẵn. Tiếp tục với series, bài này mình sẽ giới thiệu với mọi người về xử lý form trong Express: đọc dữ liệu bằng express.urlencoded() và express.json(), redirect sau POST và giữ lại dữ liệu cũ khi có lỗi.
1. Đọc body của request.
Khi các bạn submit một form method="post", trình duyệt gửi dữ liệu trong body của request dưới dạng application/x-www-form-urlencoded (VD: title=Hello&content=...). Client gọi API thường gửi JSON (application/json).
Express không tự đọc body: như ở Bài 5, req.body là undefined cho đến khi có middleware đọc body. Express có sẵn hai built-in middleware cho hai định dạng trên:
express.urlencoded(options): đọc dữ liệu form.express.json(options): đọc JSON.
Mỗi middleware chỉ đọc request có Content-Type đúng định dạng của nó và gán kết quả vào req.body. Hai option hay dùng:
limit: dung lượng body tối đa, mặc định'100kb'. Body lớn hơn bị từ chối với lỗi 413 (chi tiết ở Bài 17).extended(chỉ có ởurlencoded): cách đọc tên field dạnga[b], xem phần 2.
Các bạn thêm hai middleware vào app.js, trước các router:
- app.js (thêm ngay sau dòng express.static())
// Đọc body dạng form (urlencoded) và JSON vào req.body
app.use(express.urlencoded());
app.use(express.json());
2. Tùy chọn extended trong Express 5.
Ở Express 5, express.urlencoded() có extended mặc định là false (Express 4 là true, xem Bài 1). Lúc này tên field như author[name] được giữ nguyên làm key, không tạo object lồng nhau. Field lặp lại nhiều lần vẫn thành array ở cả hai chế độ.
VD: Các bạn tạo file body.js trong thư mục miniblog để so sánh:
- body.js
import express from 'express';
const app = express();
// extended: false (mặc định ở Express 5)
app.post('/simple', express.urlencoded(), (req, res) => {
res.json(req.body);
});
// extended: true (mặc định ở Express 4)
app.post('/extended', express.urlencoded({ extended: true }), (req, res) => {
res.json(req.body);
});
app.listen(4000, () => console.log('http://localhost:4000'));
Chạy node body.js rồi gửi cùng một body tới hai route (curl -d gửi dữ liệu dạng form):
curl -d 'tags=express&tags=node&author[name]=Tai' http://localhost:4000/simple
# {"tags":["express","node"],"author[name]":"Tai"}
curl -d 'tags=express&tags=node&author[name]=Tai' http://localhost:4000/extended
# {"tags":["express","node"],"author":{"name":"Tai"}}
Form của MiniBlog chỉ có field đơn giản nên mình giữ mặc định. Thử xong các bạn tắt server (Ctrl + C) và xoá file body.js.
3. Form tạo bài viết.
Form viết bài của MiniBlog gửi POST tới /posts, thuộc tính name của mỗi field sẽ là key trong req.body:
- views/posts/new.ejs (đường dẫn của include() tính từ file hiện tại nên có ../)
<%- include('../partials/header') %>
<h1><%= title %></h1>
<% if (error) { %>
<p class="error"><%= error %></p>
<% } %>
<form method="post" action="/posts">
<p>
<label for="title">Tiêu đề</label><br>
<input id="title" name="title" value="<%= old.title %>">
</p>
<p>
<label for="content">Nội dung</label><br>
<textarea id="content" name="content" rows="8"><%= old.content %></textarea>
</p>
<button type="submit">Đăng bài</button>
</form>
<%- include('../partials/footer') %>
Hai route mới nằm trong routes/posts.js. Route /new phải đặt trước /:slug, nếu không new sẽ bị hiểu là một slug (thứ tự khớp route ở Bài 3):
import express from 'express';
import posts from '../data/posts.js';
import HttpError from '../lib/http-error.js';
const router = express.Router();
// Lấy chuỗi đã bỏ khoảng trắng hai đầu, giá trị không phải chuỗi coi như rỗng
function text(value) {
return typeof value === 'string' ? value.trim() : '';
}
// Tạo slug từ tiêu đề: bỏ dấu tiếng Việt, ký tự khác chữ và số thành dấu gạch ngang
function slugify(title) {
return title
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '') // bỏ dấu thanh, dấu mũ đã tách ra bằng NFD
.replace(/đ/gi, 'd')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
// GET /posts: danh sách bài viết
router.get('/', (req, res) => {
res.json(posts);
});
// GET /posts/new: form viết bài, phải đặt trước /:slug
router.get('/new', (req, res) => {
res.render('posts/new', { title: 'Viết bài mới', error: null, old: {} });
});
// POST /posts: nhận dữ liệu form và tạo bài viết
router.post('/', (req, res) => {
const body = req.body ?? {};
const old = { title: text(body.title), content: text(body.content) };
// Thiếu dữ liệu: render lại form kèm dữ liệu cũ
if (!old.title || !old.content) {
return res.status(422).render('posts/new', {
title: 'Viết bài mới',
error: 'Vui lòng nhập đầy đủ tiêu đề và nội dung',
old,
});
}
const id = posts.length + 1;
posts.push({ id, title: old.title, slug: `${slugify(old.title)}-${id}`, content: old.content });
// PRG: chuyển hướng sang trang chủ thay vì render trực tiếp
res.redirect(303, '/');
});
// GET /posts/:slug: chi tiết bài viết
router.get('/:slug', (req, res) => {
const post = posts.find((item) => item.slug === req.params.slug);
if (!post) {
throw new HttpError(404, 'Không tìm thấy bài viết');
}
res.json(post);
});
export default router;
Trong đó:
req.body ?? {}: request không có body thìreq.bodylàundefined, đọcreq.body.titlesẽ gây lỗi 500.text():req.bodydo người dùng gửi nên không tin được kiểu dữ liệu, VD field lặp lại thành array (phần 2), JSON có thể gửi số.- Slug được thêm
idở cuối để không trùng. Dữ liệu vẫn nằm trong mảngposts, nên mỗi lần server khởi động lại (kể cả khinode --watchrestart) các bài vừa tạo sẽ mất.
Cuối cùng các bạn thêm link Viết bài vào menu và class báo lỗi vào CSS:
- views/partials/header.ejs (thêm sau link Trang chủ)
<a href="/posts/new" class="<%= currentPath === '/posts/new' ? 'active' : '' %>">Viết bài</a>
- public/css/style.css (thêm vào cuối file)
.error {
color: #c00;
}
4. Redirect sau POST (PRG).
Nếu route POST render trang kết quả luôn, khi người dùng nhấn F5 trình duyệt sẽ hỏi gửi lại form và tạo thêm một bài trùng. Cách xử lý phổ biến là PRG (Post/Redirect/Get): xử lý POST xong thì redirect, trình duyệt gửi một request GET mới, F5 lúc này chỉ tải lại trang đó.
Mình dùng res.redirect(303, '/'). Status 303 See Other nói rõ trình duyệt phải dùng GET cho địa chỉ mới (mặc định 302 cũng chạy nhưng không rõ nghĩa bằng). Chạy npm run dev, mở http://localhost:3000/posts/new để thử, hoặc dùng curl (--data-urlencode mã hoá giúp dấu cách, & và tiếng Việt; số 4 trong slug đúng khi server vừa khởi động):
curl -i --data-urlencode 'title=Xử lý form trong Express' --data-urlencode 'content=Đọc dữ liệu form' http://localhost:3000/posts
# HTTP/1.1 303 See Other
# Location: /
# ...
curl -i -H 'Content-Type: application/json' -d '{"title":"Gửi JSON","content":"Tạo bài bằng express.json()"}' http://localhost:3000/posts
# HTTP/1.1 303 See Other
# ...
curl http://localhost:3000/posts/gui-json-4
# {"id":4,"title":"Gửi JSON","slug":"gui-json-4","content":"Tạo bài bằng express.json()"}
Cùng một route nhận được cả form lẫn JSON vì hai middleware đều gán vào req.body (API riêng sẽ có ở Bài 19). JSON sai cú pháp bị express.json() báo lỗi 400 và đi tới error handler ở Bài 7:
curl -H 'Content-Type: application/json' -d '{"title": "abc",}' http://localhost:3000/posts
# {"message":"Expected double-quoted property name in JSON at position 16 (line 1 column 17)"}
5. Giữ lại dữ liệu cũ khi có lỗi.
Khi dữ liệu không hợp lệ thì ngược lại: mình render lại form ngay trong request POST, kèm thông báo lỗi và object old chứa dữ liệu vừa nhập để người dùng không phải gõ lại. Status 422 cho biết dữ liệu gửi lên chưa xử lý được.
curl -i -d 'title=&content=Nội dung <b>tạm</b>' http://localhost:3000/posts
# HTTP/1.1 422 Unprocessable Entity
# ...
# <p class="error">Vui lòng nhập đầy đủ tiêu đề và nội dung</p>
# ...
# <input id="title" name="title" value="">
# ...
# <textarea id="content" name="content" rows="8">Nội dung <b>tạm</b></textarea>
Dữ liệu cũ luôn được in bằng <%= %> để escape, nếu không người dùng có thể chèn HTML vào trang (XSS, Bài 8). Thuộc tính required của HTML cũng chặn field trống, nhưng curl vẫn gửi thẳng tới server được, nên luôn phải kiểm tra ở server.
Code đầy đủ của MiniBlog sau bài này nằm ở tag bai-10 trên GitHub; các thay đổi của riêng bài này: so sánh bai-09...bai-10.
6. Lời kết.
Như vậy là chúng ta đã tìm hiểu xong xử lý form trong Express: đọc body bằng express.urlencoded() và express.json(), option extended ở Express 5, PRG và giữ dữ liệu cũ. Phần kiểm tra dữ liệu hiện mới chỉ là một câu if, bài sau mình sẽ giới thiệu với mọi người về validation dữ liệu trong Express để kiểm tra form đầy đủ, có thông báo lỗi tiếng Việt cho từng field.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments