المعرفة:: NodeJS
الحالة::مؤرشفة
المراجع:: The Complete Node.js Developer Course 3rd Edition, coggro’s Notes
- Express is a fast, unopinionated, minimalist web framework for Node.js.
Getting Started
- The simplest Express app you can create.
- This app starts a server and listens on port 3000 for connections and responds with “Hello World!” for requests to the root URL (
/
) or route. For every other path, it will respond with a 404 Not Found. - nodemon can be used to restart the server on changes.
send()
can send text, HTML, or JSON object or array.
Serving static files
- If we are using [[./, JavaScript Modules#Native JavaScript (ES6) Modules]|ES6 Modules]] instead of CommonJS Modules we will have to apply this workaround.
- Node’s
path.join()
is used to get the full absolute path to the public folder/public/
.
- Finally, we set express’s
app.use()
to serve static files.
Dynamic Pages with Templating
- Handlebars template engine will be used to serve dynamic content (on npm).
- We need to install hbs - handlebars for express package.
npm i hbs
- Next, we can set
hbs
as view engine of express.
- By default, views are expected to be found in
/views/
directory. - Instead of using
res.send()
, we need to useres.render(viewName)
to render our views. res.render()
also accepts a second argument which is the dynamic values to pass to the view.
Customizing Views and Partials Directories
- We can change the location and name of the views directory.
- Also, we can do the same for partials directory.
Partials and Advanced Templating
- Partials are small parts of markup than can exist in different templates, e.g. headers or footers.
- It can help unifying the website look without having much duplicated markup.
- Partials can load in on other pages using
{{>partial}}
syntax. - Nodemon won’t load the changes automatically unless we adjust our nodemon command to
nodemon src/app.js -e js,hbs
. - We can reference variables in the partial just like we do in normal templates.
Setting up 404 Pages
- Set up
app.get("*", …)
as the last route in the app.- Express looks for matches in order listed. First, it looks for static pages, then at our routes, including our final wildcard route.
- We can add sub-routes, too.
- Something like this will work above the full wildcard:
Query Strings
- A way to send data from browser to the server and get it easily using
req.qurey
.
- Express doesn’t provide a way to force requiring a query, instead we can use simple if statement.
- We can also send back query data normally in response.