技術棧選型
- Express:輕量 Web 框架,路由、中間件生態豐富
- Jade (現名 Pug):模板引擎,縮進語法、支持
include/extends/block/append
- Sequelize:ORM,支持 SQLite/MySQL/PostgreSQL,模型定義、關聯、遷移
- SQLite:零配置文件型數據庫,適合中小項目/原型開發
- Redis:Session 存儲、緩存、隊列
Jade/Pug 關鍵語法實戰
佈局繼承 (extends + block)
// layout.pug (母版頁)
doctype html
html
head
title #{title} - 管理後台
block head // 子頁可追加 CSS/JS
body
include ./includes/header
.container
block content // 子頁必填
include ./includes/footer
// article_list.pug (文章列表頁)
extends ../layout
append head
link(rel='stylesheet', href='/stylesheets/font-awesome.css')
script(src='/javascripts/bootstrap-wysiwyg.js')
block content
h1 文章管理
table.table
thead
tr
th 標題
th 分類
th 操作
tbody
each article in articleList
tr
td= article.title
td= article.category.name
td
a(href='/admin/article/edit/' + article.id) 編輯
|
a(href='/admin/article/delete/' + article.id) 刪除
局部引入 (include)
// includes/header.pug
header.navbar
a.navbar-brand(href='/') 我的網站
nav
ul.nav
li: a(href='/') 首頁
li: a(href='/admin') 後台
Sequelize 模型定義與關聯
// models/index.js 初始化 Sequelize 並掛載通用分頁方法
const Sequelize = require('sequelize');
const config = require('../config');
const sequelize = new Sequelize(config.database, config.username, config.password, {
dialect: 'sqlite',
storage: config.sqlitePath,
define: {
// 為所有模型混入分頁輔助方法
classMethods: {
pageOffset(pageNum) {
pageNum = Math.max(1, parseInt(pageNum) || 1);
return (pageNum - 1) * this.pageLimit();
},
pageLimit() { return 10; },
totalPages(total) {
const pages = Math.ceil(total / this.pageLimit());
return Array.from({length: pages}, (_, i) => i + 1);
}
}
}
});
// 文章模型
const Article = sequelize.define('Article', {
title: { type: Sequelize.STRING, validate: { notEmpty: true }},
content: { type: Sequelize.TEXT },
icon: { type: Sequelize.STRING }, // 存儲文件名
iconName: { type: Sequelize.STRING }, // 原始文件名
sequencing: { type: Sequelize.INTEGER, defaultValue: 0 }
}, {
classMethods: {
// 可在此擴展靜態方法
}
});
// 分類模型
const Category = sequelize.define('Category', {
name: { type: Sequelize.STRING, unique: true }
});
// 關聯:文章屬於分類
Article.belongsTo(Category);
Category.hasMany(Article);
module.exports = { sequelize, Article, Category };
控制器實現:分頁列表、新增、文件上傳
// controllers/article.js
const { Article, Category } = require('../models');
const formidable = require('formidable');
const path = require('path');
exports.list = (req, res) => {
const pageNum = req.query.pageNum || 1;
Article.findAndCountAll({
include: [Category],
offset: Article.pageOffset(pageNum),
limit: Article.pageLimit(),
order: [['sequencing', 'DESC'], ['createdAt', 'DESC']]
}).then(result => {
res.render('article_list', {
title: '文章管理',
articleList: result.rows,
pages: {
totalPages: Article.totalPages(result.count),
currentPage: parseInt(pageNum),
router: 'article'
}
});
});
};
exports.add = (req, res) => {
const form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, '../public/uploads');
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) return res.status(500).send('上傳失敗');
// 關鍵:跨平台獲取文件名
const icon = path.basename(files.icon.path); // 自動處理 Windows \ 和 Unix /
const iconName = files.icon.name;
Article.sync().then(() => {
return Category.findById(fields.category);
}).then(category => {
const article = Article.build({
title: fields.title,
content: fields.content,
minContent: fields.minContent,
icon,
iconName,
sequencing: fields.sequencing === '0' ? 0 : 1
});
return article.save().then(a => a.setCategory(category));
}).then(() => {
res.redirect('/admin/article');
}).catch(err => {
console.error(err);
res.status(500).send('保存失敗');
});
});
};
關鍵踩坑記錄
| 問題 | 原因 | 解決 |
| Windows 部署上傳文件名亂碼/路徑錯誤 | 用字符串截取路徑,Windows 用 \,Linux 用 / | 用 path.basename(file.path) 統一獲取文件名 |
| SQLite 並發寫入鎖死 | SQLite 文件鎖機制,不適合高並發寫入 | 生產環境遷移至 MySQL/PostgreSQL |
| Sequelize 異步回調地獄 | 早期版本 Promise 未完全鏈式 | 升級 Sequelize 4+,全面使用 Promise/async-await |
| Jade 模板變量未轉義導致 XSS | 直接輸出用戶輸入 | Pug 默認轉義,用 != 才不轉義,謹慎使用 |
部署建議
- 使用 PM2 進程管理:
pm2 start app.js --name myapp
- 反向代理:Nginx 代理 3000 端口,配置靜態資源緩存
- 環境變量區分配置:
config/development.js, config/production.js
- 日誌:
winston 或 morgan 記錄訪問/錯誤日誌
copyright ©
萬盛學電腦網 all rights reserved