在日常項目中,我喜歡用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> <h2 >人物介紹</h2> {{#each personInfoList}} <h3>昵稱:{{this.name}}</h3> <h3>年齡:{{this.age}}</h3> <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后端框架也就一通百通了
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。