Q. What is Express ?
A web application framework for Node.js
Q. Express vs Express-generator ?
The express package is the framework that exposes functionalities you can use in your code
The express-generator package a utility that provides a command-line tool you can use to scaffold your project - ie create boilerplate folder structure, files and code.
Q. How to install Express and Express-generator in Node.js?
Moving into your working directory
npm install -g express-generator
npm install -g express
Q. 如何利用 express-generator 建立一個server基本框架 ?
在現行工作目錄中建立一個名為 myapp 的 Express 應用程式, 使用pug為template engine
express --view=pug myapp
安裝相依項目
cd myapp
npm install
執行應用程式
npm start
Q.app.use([path,] callback [, callback...])
Description
Mounts the specified middleware function or functions at the specified path: the middleware callback functions executed when the base of the requested path matches path.
A router is valid middleware.
An Express app is valid middleware.
path : default is ‘/’ (root path)
callback : callback functions
middleware callback function examples
如何使用中介軟體(How to use middleware callback functions)
next() : It passes control to the next matching route.
Q. 如何使用 '/user/:id' ?
In following example, it will route /user/anything, and then req.params.id = ‘anything’
app.use('/user/:id', function(req, res, next) {
console.log('Request Id:', req.params.id);
// do something with req.params.id
next();
});
Q. express.static 用法
server 端 =>提供public資料夾中的靜態檔案
app.use(express.static('public'));
client 端 => 使用public資料夾中的檔案
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
server 端 => 提供虛擬路徑, 把public資料夾掛載在 /static
app.use('/static', express.static('public'));
app.use('/static', express.static(__dirname + '/public'));
client 端 => 使用虛擬路徑
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
Q. 如何處理404回應?
在 Express 中,404 回應並不是錯誤的結果,因此錯誤處理常式中介軟體不會擷取它們。會有此行為是因為404 回應僅表示沒有額外的工作來執行;換句話說,Express 已執行所有的中介軟體函數和路由,並發現它們都沒有回應。您唯一要做的是在堆疊的最底端(其他所有函數下方),新增一個中介軟體函數,以處理 404 回應:
// middleware function to catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
next() : It passes control to the next matching route
// error handler
app.use(function(err, req, res, next) {
// render the error page
res.status(err.status || 500);
res.render('error');
});
“res.render”是使用模板引擎的語法,並將其產生的頁面直接返回给client端
res.render( 'index', {
title : 'To-Do List'
});
第一個參數是樣板名稱
第二個參數是傳遞給樣板的資料,帶到client畫面上
Q. 使用模板引擎 / 樣板引擎 (Template Engine)
指定頁面模板位置,在views子目錄下
app.set('views', path.join(__dirname, 'views'));
表明要使用的模板引擎是ejs
app.set('view engine', 'ejs');