Express新手入坑筆記之動態渲染HTML
- 在日常專案中,我喜歡用Django做後端, 因為大而全
- 如果只是寫一個簡單服務的話, Express是更好的選擇, Express是基於nodejs的一個後端框架,特點是簡單,輕量, 容易搭建, 而且效能非凡,下面我們就用最少的步驟搭建一個Express的後端服務吧!
建立資料夾
mkdir express-simple-server

初始化專案
cd express-simple-server npm init -y

安裝Express
npm install express
在根目錄下建立 express-simple-sever.js
作為入口檔案(我比較喜歡用專案名作為入口檔案), 並修改package.json檔案

{ "name": "express-simple-server", "version": "1.0.0", "description": "", "main": "express-simple-server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node express-simple-server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.16.4" } }
為express-simple-server.js新增 首頁
, about頁面
, 定製化404頁面
, 定製化500頁面
的處理邏輯
const express = require('express'); const app = express(); // 如果在環境變數內, 設定了程式執行埠,則使用環境變數設定的埠號, 否則使用3000埠 app.set('port', process.env.PORT || 3000); // 匹配根路由 / (如果不特別指明返回的狀態碼, 則預設返回200) app.get('/', function(req, res) { res.type('text/plain'); res.send('訪問了首頁'); }); // 匹配/about路由 app.get('/about', function(req, res) { res.type('text/plain'); res.send('訪問了about頁面'); }); // 定製 404 頁面 (返回404狀態碼) app.use(function(req, res) { let currentTime = new Date(); res.type('text/plain'); res.status(404); res.send('404 - 你訪問的頁面可能去了火星\n' + currentTime); }); //定製 500 頁面 (返回500狀態碼) app.use(function(err, req, res, next) { let currentTime = new Date(); let errInfo = err.stack; res.type('text/plain'); res.status(500); res.send('500 - 伺服器發生錯誤\n' + 'errInfo:' + errInfo + '\n' + 'currentTime:' + currentTime); }); // 監聽服務埠, 保證程式不會退出 app.listen(app.get('port'), function() { console.log('Express 服務正在執行在 http://localhost:' + app.get('port') + '; 按 Ctrl-C 關閉服務.'); });
讓Express跑起來
npm run start

- 訪問根路由
/

- 訪問
/about

- 觸發
404

- 觸發
500
(故意改錯了一些程式碼, 即可觸發此效果)

配置靜態檔案目錄

// 匹配靜態檔案目錄 app.use(express.static(__dirname + '/public'));
- 在根目錄下新建
public
資料夾, 在public
資料夾內新建static
資料夾

public
不會顯示在url中, 為了方便判別靜態檔案的url請求, 我們在public內新建一個static資料夾, 這樣所有請求靜態檔案的url,都會以static開頭(這裡借鑑了django處理靜態檔案的方法)
- 訪問
http://localhost:3000/static/index.html

- 訪問
http://localhost:3000/static/images/1.jpg

-
後端服務的處理邏輯都是大同小異的:
第一步: 收到前端請求
第二步: 匹配路由
第三步: 根據路由找到對應的檢視函式
第四步: 檢視函式執行內部邏輯(查資料庫, 讀取html模板), 將產生的資料, 返回給前端
使用handlebars模板引擎, 動態渲染html檔案
- 安裝模板引擎
express-handlebars
npm install express-handlebars
- 在express-simple-server.js內配置express-handlebars模板引擎
const exphbs = require('express-handlebars'); // 配置模板引擎 app.engine('html', exphbs({ layoutsDir: 'views', defaultLayout: 'layout', extname: '.html' })); app.set('view engine', 'html');
- 修改根路徑處理函式
// 匹配根路由 / (如果不特別指明返回的狀態碼, 則預設返回200) app.get('/', function(req, res) { res.render('index', { layout: false, title: "首頁", personInfoList: [{ name: "王炮兒(一拳超人)", age: 20 }, { name: "炮姐(御阪美琴)", age: 15 }] }); });
- 在根目錄下建立資料夾
views
, 並建立index.html
,

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{title}}</title> </head> <body> <h1 style="color: #64B587">人物介紹</h1> {{#each personInfoList}} <h2>暱稱:{{this.name}}</h2> <h2>年齡:{{this.age}}</h2> <hr> {{/each}} </body> </html>
- 最終效果

express-simple-server.js
原始碼
const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); // 配置模板引擎 app.engine('html', exphbs({ layoutsDir: 'views', defaultLayout: 'layout', extname: '.html' })); app.set('view engine', 'html'); // 如果在環境變數內, 設定了程式執行埠,則使用環境變數設定的埠號, 否則使用3000埠 app.set('port', process.env.PORT || 3000); // 匹配靜態檔案目錄 app.use(express.static(__dirname + '/public')); // 匹配根路由 / (如果不特別指明返回的狀態碼, 則預設返回200) app.get('/', function(req, res) { res.render('index', { layout: false, title: "首頁", personInfoList: [{ name: "王炮兒(一拳超人)", age: 20 }, { name: "炮姐(御阪美琴)", age: 15 }] }); }); // 定製 404 頁面 (返回404狀態碼) app.use(function(req, res) { let currentTime = new Date(); res.type('text/plain'); res.status(404); res.send('404 - 你訪問的頁面可能去了火星\n' + currentTime); }); //定製 500 頁面 (返回500狀態碼) app.use(function(err, req, res, next) { let currentTime = new Date(); let errInfo = err.stack; res.type('text/plain'); res.status(500); res.send('500 - 伺服器發生錯誤\n' + 'errInfo:' + errInfo + '\n' + 'currentTime:' + currentTime); }); // 監聽服務埠, 保證程式不會退出 app.listen(app.get('port'), function() { console.log('Express 服務正在執行在 http://localhost:' + app.get('port') + '; 按 Ctrl-C 關閉服務.'); });
- package.json
{ "name": "express-simple-server", "version": "1.0.0", "description": "", "main": "express-simple-server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node express-simple-server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.16.4", "express-handlebars": "^3.0.0" } }
小結:
如果你想通過一門程式語言實現全棧, javascript是你的不二之選(其實也沒得選,瀏覽器能執行的圖靈完備的語言只有javascript), Express是一個很基礎的nodejs框架, 把Express學通, 其他nodejs後端框架也就一通百通了