1. Basic
Install
Basic Setup
Starting the server, keep restarting everytimes codes changed with nodemon
2. Response Objects
HTML (for web pages in browser)
JSON (for RestAPI)
Response will be auto convert to JSON.stringlify() You can use an array of objects Serve an entire directory (website with JS, CSS)
Popular file structure
public (for public assets) src (for starting JS file) templates (for handlebars files - just like views and includes) partials (includes like headers, footer, navigation)
Path Management to link to different folders & files
We could use these default var to manage paths, but we need a more absolute way to manage path.... When we serve a public static folder, we don’t need according routes. the idea of a public static folder is to serve static assets, static HTML we need a solution to serve dynamic pages Serve dynamic pages
Use template engine ‘handlebars’
Actually, we should use handlebar for express, which is here:
Install into local application
Set default template engine in express
To use template engine, we need to use:
templates / partials / views folders files has to be put in right folders no need to declare file ext .hbs Be careful because res.render use index.hbs, but express will show public/index.html if available
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
to stop after the first response, use return 3. Query String
localhost:1234/weather?location=Hanoi
Use req.query
4. Integrate with back-end JS
File Structure
Back-end code in src
export JSON via HTTP end-point 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:
fetch (this fetch is only for client side, surprise!!!! not accessiable in Node.js) Steps to Integration
Build back-end code
Use app.js and route to build HTTP endpoint Return JSON via HTTP endpoint (query string or POST) Build front-end templates
Get JSON and parse into DOM Tham khảo node-fetch
hàm core fetch chỉ xài được ở browser client hàm node-fetch giống y chang, xài được ở back-end Bài viết Tham khảo
This link can't be embedded.
This link can't be embedded.