Node.js 是一個基於 Chrome V8 引擎的 JavaScript 運行環境,能夠在伺服器端運行 JavaScript。而 Express 框架則是 Node.js 中最流行的 Web 框架之一,它提供了一些常用的功能和工具,使得開發者能夠快速構建 Web 應用程序。本文將重點介紹如何使用 Express 框架打造高效的 Node.js Web 應用。
一、安裝和使用 Express 框架
在開始使用 Express 框架之前,需要先安裝它。可以通過 NPM(Node.js 包管理器)來安裝。打開終端並輸入以下命令:
npm install express --save
運行以上命令後,會自動下載並安裝 Express 框架,安裝完後我們就可以開始使用了。
要在 Node.js 項目中使用 Express,需要在項目中引入它。在代碼中添加以下代碼:
const express = require('express');
const app = express();
上述代碼中,我們用 require 函數將 Express 模塊引入,並將其創建為 app 變數的值。
接下來,我們可以通過 app 變數的方法來訪問 Express 框架的功能,比如設置路由、處理 HTTP 請求等。以下是使用 Express 框架設置路由的示例代碼:
app.get('/', function (req, res) {
res.send('Hello World!');
});
上述代碼中,我們使用 app.get() 方法來設置路由。當用戶訪問根 URL(’/’)時,會調用回調函數,該函數會返回「Hello World!」作為響應。
二、Express 中間件
Express 中間件是 Web 應用程序中用於處理 HTTP 請求的函數。它們通過修改請求或響應對象、執行任意代碼、結束請求-響應循環等來擴展 Express 框架的功能。
以下是一個簡單的 Express 中間件示例,它用於記錄每個請求的時間和請求方法:
const myMiddleware = function (req, res, next) {
console.log('Request received:', Date.now(), req.method);
next();
};
app.use(myMiddleware);
上述代碼中,我們定義了一個名為 myMiddleware 的中間件函數,並使用 app.use() 方法將它註冊為全局中間件。當任何 HTTP 請求被發出時,都會先經過該中間件函數,因為它被註冊為全局中間件。
三、使用 Express 構建 RESTful API
REST(Representational State Transfer)是一個架構風格,用於 Web 服務。RESTful API 提供了一組 Web APIs,用於創建、讀取、更新和刪除數據。它們使用 HTTP 協議的 GET、POST、PUT 和 DELETE 請求來實現這些操作。
以下是一個使用 Express 構建 RESTful API 的示例代碼:
const express = require('express');
const app = express();
app.use(express.json());
let users = [
{ id: 1, name: 'alice' },
{ id: 2, name: 'bob' },
{ id: 3, name: 'charlie' },
];
app.get('/users', function (req, res) {
res.send(users);
});
app.post('/users', function (req, res) {
const newUser = req.body;
users.push(newUser);
res.send('User added successfully');
});
app.put('/users/:id', function (req, res) {
const idToUpdate = req.params.id;
const updatedUser = req.body;
users = users.map(user => {
if (user.id == idToUpdate) {
return updatedUser;
}
return user;
});
res.send('User updated successfully');
});
app.delete('/users/:id', function (req, res) {
const idToDelete = req.params.id;
users = users.filter(user => user.id != idToDelete);
res.send('User deleted successfully');
});
app.listen(3000, function () {
console.log('Server started on port 3000');
});
上述代碼中,我們創建了一個 RESTful API,允許用戶進行以下操作:
– GET:獲取所有用戶的信息
– POST:添加一個新用戶
– PUT:更新現有用戶的信息
– DELETE:刪除現有的用戶
四、使用模板引擎渲染動態頁面
Express 中可以使用多種模板引擎來動態渲染 HTML 頁面,比如 EJS、Pug 和 Handlebars。這些模板引擎基於 HTML 和 JavaScript,可以使用響應式數據來生成 HTML 文件。
以下是一個使用 EJS 模板引擎渲染動態頁面的示例代碼:
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
const greeting = 'Welcome to my website!';
res.render('index', { greeting: greeting });
});
app.listen(3000, function () {
console.log('Server started on port 3000');
});
在上述代碼中,我們首先使用 app.set() 方法設置視圖引擎為 EJS。接下來,我們使用 res.render() 方法將動態數據(greeting 變數的值)傳遞到視圖文件 index.ejs 中,生成 HTML 文件並將其返回給客戶端。
五、使用 Express 處理表單提交
在 Web 開發中,表單提交是很常見的一種用戶行為。要在 Express 中處理表單提交,需要使用 body-parser 中間件來解析 POST 請求的正文數據。
以下是一個使用 Express 處理表單提交的示例代碼:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/form', function (req, res) {
res.render('form');
});
app.post('/submit', function (req, res) {
const username = req.body.username;
const password = req.body.password;
res.render('result', { username: username, password: password });
});
app.listen(3000, function () {
console.log('Server started on port 3000');
});
在上述代碼中,我們使用 body-parser 中間件來解析 POST 請求的正文數據,並使用 res.render() 方法將表單提交的數據顯示在 result 視圖文件中。
六、使用 Express 實現用戶認證
用戶認證是一種常見的 Web 應用程序功能,它通過驗證用戶名和密碼來授權用戶訪問受保護的頁面。Express 可以與多種用戶認證庫集成,比如 Passport.js 和 OAuth。
以下是一個使用 Passport.js 實現用戶認證的示例代碼:
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const app = express();
app.set('view engine', 'ejs');
passport.use(new LocalStrategy(function (username, password, done) {
if (username === 'admin' && password === 'password123') {
return done(null, { username: username });
}
return done(null, false, { message: 'Incorrect username or password' });
}));
passport.serializeUser(function (user, done) {
done(null, user.username);
});
passport.deserializeUser(function (username, done) {
done(null, { username: username });
});
app.use(require('express-session')({
secret: 'mysecretkey',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', function (req, res) {
res.render('home', { user: req.user });
});
app.get('/login', function (req, res) {
res.render('login');
});
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}));
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
function requireAuth(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
}
app.get('/dashboard', requireAuth, function (req, res) {
res.render('dashboard', { user: req.user });
});
app.listen(3000, function () {
console.log('Server started on port 3000');
});
在上述代碼中,我們使用 Passport.js 實現了用戶認證的功能。用戶輸入用戶名和密碼後,如果驗證通過,會返回一個包含用戶名的對象。在登錄過程中,我們使用了 Express Session 中間件來管理用戶會話。除此之外,我們還使用了 requireAuth 函數來處理受保護的 dashboard 頁面,該函數會檢查用戶是否已通過身份驗證,如果沒有,會重定向到登錄頁面。
七、總結
本文介紹了使用 Express 框架打造高效的 Node.js Web 應用的方法。我們提到了如何安裝和使用 Express 框架、使用中間件來擴展 Express 的功能、如何構建 RESTful API、使用模板引擎渲染動態頁面、處理表單提交和用戶認證等。對於 Web 開發人員來說,掌握這些技能可以增強他們的技能水平,並提高他們的生產力。
原創文章,作者:IHPZ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/130990.html