Express Web Server
Install Express
Install
Basic Setup
Starting the server, keep restarting everytimes codes changed with nodemon
Middleware
Middleware is the nature of express.
Body Parser
Express add new req.body and res.redirect
In order to use req.body , we need to install bodyParser
So far
Summary of app.use('/') vs app.get('/') Confusion
Router
Why using both app.use and router.use
In Express.js, app.use and router.use serve similar purposes but are used in different contexts. Here's the breakdown:
app.use
router.use
Why use express.Router()?
express.Router() is used to create modular, mountable route handlers. It helps organize your application by separating routes into smaller, manageable pieces. This is especially useful for large applications.
Benefits of express.Router():
Example of express.Router() in a modular app:
Key Difference
Helper or Utils
Constructing a helper to define a root dir for res.sendFile(’page.html’)
Static Public Folder
Next hay Không Next
1. next() là gì và khi nào thì “đi tiếp”?
Trong Express, mỗi request sẽ đi qua một chuỗi middleware/route handler.
Mỗi “chặng” trong chuỗi đó là một function kiểu:
Nói ngắn gọn:
next() dùng khi bạn chưa muốn kết thúc request, mà chỉ làm một bước xử lý rồi chuyển tiếp cho thằng kế tiếp.
2. Vì sao bodyParser.urlencoded(...) và express.static(...) không thấy
next() mà vẫn đi tiếp?
Thực ra là có next(), chỉ là nó nằm bên trong function mà những dòng đó trả về.
Ví dụ:
Hai cái này không phải middleware trực tiếp.
Chúng là factory function – gọi xong thì trả về một middleware dạng:
Bạn có thể tưởng tượng:
urlencodedMiddleware bên trong có next():
Tương tự với:
staticMiddleware sẽ:
Nên lý do bạn không thấy next() là vì:
next() ở bên trong middleware mà những hàm đó trả về, chứ không nằm ở chỗ bạn viết.
3. res.send() và res.sendFile() có “tự động stop code” không?
Có 2 ý phải tách ra:
3.1. Về phía HTTP response
Khi bạn gọi:
hoặc
thì Express sẽ:
Sau đó:
3.2. Về phía JavaScript code trong handler
res.send() không phải là return. Nó không tự động dừng function của bạn.
Code phía sau vẫn chạy bình thường:
Muốn “stop code” trong handler tại chỗ res.send(), bạn nên return luôn:
Pattern thực tế hay dùng là:
4. Tóm lại cho dễ nhớ
Sending Response
HTML
JSON (for RestAPI)
Serve an entire directory (website with JS, CSS)
Popular file structure
Path Management to link to different folders & files
Serve dynamic pages
Use template engine ‘handlebars’
This embedded link can't be shown.
Actually, we should use handlebar for express, which is here:
This embedded link can't be shown.
Install into local application
Set default template engine in express
To use template engine, we need to use:
The hbs files are basically the same with html files, except for placeholders in this format:
Partials are just like includes (for menu, header...)
To use hbs template without partials, there is no need to require hbs.
BUT to use partials, you HAVE TO require hbs module.
When you change the handble bars partials, nodemon will not auto restart, so you have to extend its scope
To include partials in view files
Serve Error Pages
Handler page for “No page found”
Place this route at the end of the file, below all other routes
You can’s send response twice
Retrieving Data from Request
1. GET Request
To retrieve data via a GET request, you can extract parameters from the URL. Here's an example using Express:
2. POST Request
For a POST request, you often want to receive data from the request body. Make sure to use middleware like body-parser to parse JSON.
Serving Dynamic URL Response
4. Integrate with back-end JS
File Structure
Back-end code in src
Front-end code in public
app.js is the starting point (but in src, act as router as well)
Back-end code modules:
Front-end code modules:
Steps to Integration
Build back-end code
Build front-end templates
Tham khảo node-fetch
This embedded link can't be shown.
Bài viết Tham khảo
This embedded link can't be shown.
This embedded link can't be shown.
This embedded link can't be shown.
This embedded link can't be shown.
This embedded link can't be shown.
Working with Database
This embedded link can't be shown.
