零成本自建碎碎念API
前言
未完待续,周末遇到了点紧急状况,所以先放着,后面再补上
一套碎碎念的API其实就是简单的CRUD,但是部署总是要成本的,本篇文章将提供一个轻量级的零成本方案,具体方案如下
- 白嫖MongoDB作为数据库
- 部署Vercel API,提供CRUD接口
- 由于Vercel被墙了,但Cloudflare Workers是可以在大陆访问的,所以可以部署Cloudflare Worker作为代理(为什么不直接用Cloudflare提供API呢?
最终效果请见
白嫖MongoDB
- 注册MongoDB账号:https://www.mongodb.com/zh-cn/cloud/atlas/register
- 创建集群
- 复制连接信息
- 我们可以先通过navicat连接MongoDB,便于我们后期管理博客内容
部署Vercel API
- 注册Vercel:https://vercel.com/login
- 安装Vercel CLI并登录
1
2npm install -g vercel
vercel login
- 选择自己的登录方式
- 如果选择了邮箱登录,在发验证码的时候有可能会失败,这里建议配置代理
1
2
3HTTP_PROXY=http://127.0.0.1:7890
HTTPS_PROXY=http://127.0.0.1:7890
vercel login - 登录成功如下
- 创建项目文件夹并进入,安装依赖
1
npm install express mongoose cors
- 创建api/index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76// MongoDB 连接 URL
const uri = "mongodb+srv://<username>:<password>.@<endpoint>/?retryWrites=true&w=majority&appName=Azure-Cluster-HongKong";
// 创建 MongoDB 客户端
const client = new MongoClient(uri);
// 连接数据库
let db;
let isConnected = false; // 添加连接状态标志
// 添加根路由处理
app.get("/", (req, res) => {
res.json({ message: "API 服务器正在运行" });
});
async function connectToDatabase() {
try {
await client.connect();
db = client.db("kyle_blog_secret");
isConnected = true; // 设置连接状态
console.log("成功连接到 MongoDB");
} catch (error) {
console.error("MongoDB 连接失败:", error);
throw error;
}
}
// 添加中间件来检查数据库连接
app.use(async (req, res, next) => {
if (!isConnected) {
try {
await connectToDatabase();
} catch (error) {
return res.status(500).json({ message: "数据库连接失败", error: error.message });
}
}
next();
});
// 修改查询接口
app.get("/query", async (req, res) => {
try {
if (!db) {
throw new Error("数据库连接未就绪");
}
const { item } = req.query;
const filter = item ? { item } : {};
const result = await db.collection("kyle").find(filter).toArray();
res.json(result);
} catch (error) {
console.error("查询失败:", error);
res.status(500).json({ message: "查询失败", error: error.message });
}
});
// 心跳接口
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
// 错误处理中间件
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: "服务器内部错误", error: err.message });
});
// 启动服务器
if (process.env.NODE_ENV !== 'production') {
app.listen(port, () => {
console.log(`服务器运行在端口 ${port}`);
});
}
module.exports = app; - 根目录创建vercel.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15{
"version": 2,
"builds": [
{
"src": "api/index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/.*",
"dest": "api/index.js"
}
]
}
- 最终的目录结构是这样的
部署Cloudflare Worker作为代理
修改DNS
评论