詳解Express筆記之動(dòng)態(tài)渲染HTML(新手入坑)
在日常項(xiàng)目中,我喜歡用Django做后端, 因?yàn)榇蠖?/p>
如果只是寫(xiě)一個(gè)簡(jiǎn)單服務(wù)的話(huà), 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('訪(fǎng)問(wèn)了首頁(yè)');
});
// 匹配/about路由
app.get('/about', function(req, res) {
res.type('text/plain');
res.send('訪(fǎng)問(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 - 你訪(fǎng)問(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
訪(fǎng)問(wèn)根路由 /
訪(fǎng)問(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)文件的方法)
訪(fǎng)問(wèn) http://localhost:3000/static/index.html
訪(fǎng)問(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>昵稱(chēng):{{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 - 你訪(fǎng)問(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)文章
基于Node.js的WebSocket通信實(shí)現(xiàn)
這篇文章主要介紹了基于Node.js的WebSocket通信實(shí)現(xiàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-03-03
nodejs實(shí)現(xiàn)郵件發(fā)送服務(wù)實(shí)例分享
本文給大家講解的是簡(jiǎn)單的使用nodejs搭建郵件發(fā)送服務(wù)的一個(gè)實(shí)例,非常的好用,有需要的小伙伴可以參考下2017-03-03
使用nodejs搭建一個(gè)簡(jiǎn)易HTTP服務(wù)的實(shí)現(xiàn)示例
本文主要介紹了使用nodejs搭建一個(gè)簡(jiǎn)易HTTP服務(wù)的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
Nodejs進(jìn)階:核心模塊net入門(mén)學(xué)習(xí)與實(shí)例講解
本篇文章主要是介紹了Nodejs之NET模塊,net模塊是同樣是nodejs的核心模塊,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-11-11
Node.js安裝詳細(xì)步驟教程(Windows版)詳解
這篇文章主要介紹了Node.js安裝詳細(xì)步驟教程(Windows版),本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09
async/await優(yōu)雅的錯(cuò)誤處理方法總結(jié)
這篇文章主要給大家介紹了關(guān)于async/await優(yōu)雅的錯(cuò)誤處理方法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
node?NPM庫(kù)glob通配符匹配文件名minimatch模式匹配字符串學(xué)習(xí)
這篇文章主要為大家介紹了node?NPM庫(kù)glob通配符匹配文件名minimatch模式匹配字符串學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07

