詳解Express筆記之動(dòng)態(tài)渲染HTML(新手入坑)
在日常項(xiàng)目中,我喜歡用Django做后端, 因?yàn)榇蠖?/p>
如果只是寫(xiě)一個(gè)簡(jiǎn)單服務(wù)的話, Express是更好的選擇, Express是基于nodejs的一個(gè)后端框架,特點(diǎn)是簡(jiǎn)單,輕量, 容易搭建, 而且性能非凡,下面我們就用最少的步驟搭建一個(gè)Express的后端服務(wù)吧!
創(chuàng)建文件夾
mkdir express-simple-server
初始化項(xiàng)目
cd express-simple-server npm init -y
安裝Express
npm install express
在根目錄下創(chuàng)建 express-simple-sever.js
作為入口文件(我比較喜歡用項(xiàng)目名作為入口文件), 并修改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添加 首頁(yè)
, about頁(yè)面
, 定制化404頁(yè)面
, 定制化500頁(yè)面
的處理邏輯
const express = require('express'); const app = express(); // 如果在環(huán)境變量?jī)?nèi), 設(shè)定了程序運(yùn)行端口,則使用環(huán)境變量設(shè)定的端口號(hào), 否則使用3000端口 app.set('port', process.env.PORT || 3000); // 匹配根路由 / (如果不特別指明返回的狀態(tài)碼, 則默認(rèn)返回200) app.get('/', function(req, res) { res.type('text/plain'); res.send('訪問(wèn)了首頁(yè)'); }); // 匹配/about路由 app.get('/about', function(req, res) { res.type('text/plain'); res.send('訪問(wèn)了about頁(yè)面'); }); // 定制 404 頁(yè)面 (返回404狀態(tài)碼) app.use(function(req, res) { let currentTime = new Date(); res.type('text/plain'); res.status(404); res.send('404 - 你訪問(wèn)的頁(yè)面可能去了火星\n' + currentTime); }); //定制 500 頁(yè)面 (返回500狀態(tài)碼) 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 - 服務(wù)器發(fā)生錯(cuò)誤\n' + 'errInfo:' + errInfo + '\n' + 'currentTime:' + currentTime); }); // 監(jiān)聽(tīng)服務(wù)端口, 保證程序不會(huì)退出 app.listen(app.get('port'), function() { console.log('Express 服務(wù)正在運(yùn)行在 http://localhost:' + app.get('port') + '; 按 Ctrl-C 關(guān)閉服務(wù).'); });
讓Express跑起來(lái)
npm run start
訪問(wèn)根路由 /
訪問(wèn) /about
觸發(fā) 404
觸發(fā) 500
(故意改錯(cuò)了一些代碼, 即可觸發(fā)此效果)
配置靜態(tài)文件目錄
// 匹配靜態(tài)文件目錄 app.use(express.static(__dirname + '/public'));
在根目錄下新建 public
文件夾, 在 public
文件夾內(nèi)新建 static
文件夾
這里的 public
不會(huì)顯示在url中, 為了方便判別靜態(tài)文件的url請(qǐng)求, 我們?cè)趐ublic內(nèi)新建一個(gè)static文件夾, 這樣所有請(qǐng)求靜態(tài)文件的url,都會(huì)以static開(kāi)頭(這里借鑒了django處理靜態(tài)文件的方法)
訪問(wèn) http://localhost:3000/static/index.html
訪問(wèn) http://localhost:3000/static/images/1.jpg
后端服務(wù)的處理邏輯都是大同小異的:
第一步: 收到前端請(qǐng)求
第二步: 匹配路由
第三步: 根據(jù)路由找到對(duì)應(yīng)的視圖函數(shù)
第四步: 視圖函數(shù)執(zhí)行內(nèi)部邏輯(查數(shù)據(jù)庫(kù), 讀取html模板), 將產(chǎn)生的數(shù)據(jù), 返回給前端
使用handlebars模板引擎, 動(dòng)態(tài)渲染html文件
安裝模板引擎 express-handlebars
npm install express-handlebars
在express-simple-server.js內(nèi)配置express-handlebars模板引擎
const exphbs = require('express-handlebars'); // 配置模板引擎 app.engine('html', exphbs({ layoutsDir: 'views', defaultLayout: 'layout', extname: '.html' })); app.set('view engine', 'html');
修改根路徑處理函數(shù)
// 匹配根路由 / (如果不特別指明返回的狀態(tài)碼, 則默認(rèn)返回200) app.get('/', function(req, res) { res.render('index', { layout: false, title: "首頁(yè)", personInfoList: [{ name: "王炮兒(一拳超人)", age: 20 }, { name: "炮姐(御坂美琴)", age: 15 }] }); });
在根目錄下創(chuàng)建文件夾 views
, 并創(chuàng)建 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'); // 如果在環(huán)境變量?jī)?nèi), 設(shè)定了程序運(yùn)行端口,則使用環(huán)境變量設(shè)定的端口號(hào), 否則使用3000端口 app.set('port', process.env.PORT || 3000); // 匹配靜態(tài)文件目錄 app.use(express.static(__dirname + '/public')); // 匹配根路由 / (如果不特別指明返回的狀態(tài)碼, 則默認(rèn)返回200) app.get('/', function(req, res) { res.render('index', { layout: false, title: "首頁(yè)", personInfoList: [{ name: "王炮兒(一拳超人)", age: 20 }, { name: "炮姐(御坂美琴)", age: 15 }] }); }); // 定制 404 頁(yè)面 (返回404狀態(tài)碼) app.use(function(req, res) { let currentTime = new Date(); res.type('text/plain'); res.status(404); res.send('404 - 你訪問(wèn)的頁(yè)面可能去了火星\n' + currentTime); }); //定制 500 頁(yè)面 (返回500狀態(tài)碼) 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 - 服務(wù)器發(fā)生錯(cuò)誤\n' + 'errInfo:' + errInfo + '\n' + 'currentTime:' + currentTime); }); // 監(jiān)聽(tīng)服務(wù)端口, 保證程序不會(huì)退出 app.listen(app.get('port'), function() { console.log('Express 服務(wù)正在運(yùn)行在 http://localhost:' + app.get('port') + '; 按 Ctrl-C 關(guān)閉服務(wù).'); });
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" } }
小結(jié):
如果你想通過(guò)一門(mén)編程語(yǔ)言實(shí)現(xiàn)全棧, javascript是你的不二之選(其實(shí)也沒(méi)得選,瀏覽器能運(yùn)行的圖靈完備的語(yǔ)言只有javascript), Express是一個(gè)很基礎(chǔ)的nodejs框架, 把Express學(xué)通, 其他nodejs后端框架也就一通百通了
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
深入理解Commonjs規(guī)范及Node模塊實(shí)現(xiàn)
本篇文章主要介紹了深入理解Commonjs規(guī)范及Node模塊實(shí)現(xiàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05淺析Node.js的Stream模塊中的Readable對(duì)象
這篇文章主要介紹了淺析Node.js的Stream模塊中的Readable對(duì)象,是Node.js入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-07-07使用Node.js為其他程序編寫(xiě)擴(kuò)展的基本方法
這篇文章主要介紹了使用Node.js為其他程序編寫(xiě)擴(kuò)展的基本方法 ,文中示例是通過(guò)Node讓JavaScript代碼與C++應(yīng)用產(chǎn)生交互,需要的朋友可以參考下2015-06-06Node.js中package.json中庫(kù)的版本號(hào)(~和^)
這篇文章主要介紹了Node.js中package.json中庫(kù)的版本號(hào)(~和^),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-04-04iOS + node.js使用Socket.IO框架進(jìn)行實(shí)時(shí)通信示例
本篇文章主要介紹了iOS + node.js使用Socket.IO框架進(jìn)行實(shí)時(shí)通信示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-04-04node.js中的fs.appendFileSync方法使用說(shuō)明
這篇文章主要介紹了node.js中的fs.appendFileSync方法使用說(shuō)明,本文介紹了fs.appendFileSync方法說(shuō)明、語(yǔ)法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12