返回
重燃码农热情:Node.js 实战博客系统逻辑编写(终章)
前端
2023-08-10 22:23:47
博客系统实战:后端逻辑编写详解
前言
上一篇文章中,我们完成了博客系统的页面编写。今天,让我们开启激动人心的后端逻辑编写之旅,带领你领略用户管理、文章管理、评论管理、JWT 认证和系统部署的奥秘。准备好,上车!
1. 用户管理
1.1 用户注册
用户注册过程涉及以下步骤:
- 接收用户输入的用户名和密码。
- 对密码进行加密处理,保障安全性。
- 将加密后的用户信息保存到 MongoDB 中。
const bcrypt = require("bcrypt");
app.post("/register", async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const newUser = new User({
username: req.body.username,
password: hashedPassword,
});
await newUser.save();
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to register user" });
}
});
1.2 用户登录
用户登录流程如下:
- 接收用户输入的用户名和密码。
- 查询 MongoDB,验证用户是否存在。
- 对比输入密码与数据库中加密后的密码是否匹配。
- 如果密码匹配,生成 JWT token 并返回给用户。
app.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username });
if (!user) {
return res.status(404).json({ error: "User not found" });
}
const isPasswordValid = await bcrypt.compare(req.body.password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ error: "Invalid password" });
}
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });
res.json({ success: true, token });
} catch (error) {
res.status(500).json({ error: "Failed to login user" });
}
});
1.3 用户注销
用户注销过程很简单:
- 删除用户在 MongoDB 中的 session。
- 返回注销成功的响应。
app.post("/logout", async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.userId, { $unset: { session: 1 } }, { new: true });
if (!user) {
return res.status(404).json({ error: "User not found" });
}
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to logout user" });
}
});
2. 文章管理
2.1 文章发布
文章发布过程包含以下步骤:
- 接收用户输入的文章标题和内容。
- 将文章数据保存到 MongoDB 中。
- 返回发布成功的响应。
app.post("/articles", async (req, res) => {
try {
const newArticle = new Article({
title: req.body.title,
content: req.body.content,
});
await newArticle.save();
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to publish article" });
}
});
2.2 文章修改
文章修改流程如下:
- 接收用户输入的修改后的文章标题和内容。
- 更新 MongoDB 中的文章数据。
- 返回修改成功的响应。
app.put("/articles/:id", async (req, res) => {
try {
const article = await Article.findByIdAndUpdate(req.params.id, { title: req.body.title, content: req.body.content }, { new: true });
if (!article) {
return res.status(404).json({ error: "Article not found" });
}
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to modify article" });
}
});
2.3 文章删除
文章删除过程相对简单:
- 从 MongoDB 中删除指定 ID 的文章。
- 返回删除成功的响应。
app.delete("/articles/:id", async (req, res) => {
try {
const article = await Article.findByIdAndDelete(req.params.id);
if (!article) {
return res.status(404).json({ error: "Article not found" });
}
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to delete article" });
}
});
3. 评论管理
3.1 评论发布
评论发布流程与文章发布类似:
- 接收用户输入的评论内容。
- 将评论数据保存到 MongoDB 中。
- 返回发布成功的响应。
app.post("/articles/:id/comments", async (req, res) => {
try {
const newComment = new Comment({
content: req.body.content,
articleId: req.params.id,
});
await newComment.save();
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to publish comment" });
}
});
3.2 评论修改
评论修改流程如下:
- 接收用户输入的修改后的评论内容。
- 更新 MongoDB 中的评论数据。
- 返回修改成功的响应。
app.put("/comments/:id", async (req, res) => {
try {
const comment = await Comment.findByIdAndUpdate(req.params.id, { content: req.body.content }, { new: true });
if (!comment) {
return res.status(404).json({ error: "Comment not found" });
}
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to modify comment" });
}
});
3.3 评论删除
评论删除过程与文章删除类似:
- 从 MongoDB 中删除指定 ID 的评论。
- 返回删除成功的响应。
app.delete("/comments/:id", async (req, res) => {
try {
const comment = await Comment.findByIdAndDelete(req.params.id);
if (!comment) {
return res.status(404).json({ error: "Comment not found" });
}
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to delete comment" });
}
});
4. JWT 认证
4.1 JWT 生成
用户登录成功后,我们需要生成一个 JWT token:
- 使用 JWT 库,基于用户 ID 和私钥生成 token。
- 返回 token 给用户。
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });
4.2 JWT 验证
当用户访问需要鉴权的接口时,我们需要验证 JWT token:
- 从请求头中获取 token。
- 使用 JWT 库,基于 token 和公钥进行验证。
- 如果验证成功,则允许用户访问接口。
const token = req.header("Authorization").replace("Bearer ", "");
const decoded = jwt.verify(token, process.env.JWT_PUBLIC_KEY);
5. 系统部署
5.1 云服务器选择
- 选择国内知名云服务商,如阿里云、腾讯云。
5.2 代码上传
- 使用 FTP 或 Git 等工具,将代码上传到服务器。
5.3 依赖库安装
- 安装必要的依赖库,如 Node.js、MongoDB 等。
5.4 系统启动
- 启动系统,访问服务器 IP 地址,即可看到你的博客系统。
6. SEO 优化
6.1 关键词优化
- 在文章标题和内容中加入相关的关键词。
6.2 图像和视频
- 在文章中加入图片和视频,提高可读性和用户体验。
6.3 外部链接
- 在文章中加入外部链接,指向其他相关网站。
**6