摘要 :还在为前后端联调烦恼?Next.js 内置的 API 路由功能,让你仅用前端项目就能写后端接口 !本文手把手教你如何在
pages/api
目录下创建 RESTful 接口,并连接 MongoDB 数据库,实现真正的"全栈前端开发"。
一、为什么 Next.js 能写后端接口?
Next.js 是一个 React 全栈框架,从 9.4 版本开始 就内置了 API Routes(API 路由) 功能。如今最新版本是15,所以可以放心食用!
- 所有放在
pages/api
目录下的文件,都会被自动映射为 API 接口; - 每个文件就是一个独立的"微服务";
- 无需额外搭建 Node.js 服务器,部署到 Vercel 后自动变成真实接口;
- 支持连接数据库(如 MongoDB、MySQL、PostgreSQL 等)。
✅ 一句话总结:
pages/api/hello.js
→http://localhost:3000/api/hello
二、准备工作
1. 创建 Next.js 项目
bash
npx create-next-app@latest next-api-demo
cd next-api-demo
选择默认配置即可(TypeScript 可选)。
2. 安装 MongoDB 驱动
我们将使用 MongoDB Atlas(云数据库) + Mongoose(ODM):
bash
npm install mongoose
💡 如果你没有 MongoDB,可免费注册 MongoDB Atlas 创建集群。
3. 获取数据库连接字符串
在 Atlas 中创建数据库后,你会得到类似这样的连接串:
ini
mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/mydb?retryWrites=true&w=majority
将 <username>
和 <password>
替换为你的账号密码,并创建一个数据库(如 nextapi
)。
三、创建用户模型(Model)
在项目根目录新建 models/User.js
:
js
// models/User.js
import { Schema, model, models } from 'mongoose';
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
createdAt: { type: Date, default: Date.now }
});
// 防止重复注册模型(Next.js 热重载会多次执行)
const User = models.User || model('User', userSchema);
export default User;
四、编写 API 接口:RESTful 用户管理
在 pages/api
下创建 users
目录,并新建 index.js
文件:
bash
pages/
└─ api/
└─ users/
└─ index.js ← 本文件
pages/api/users/index.js
内容如下:
js
// pages/api/users/index.js
import { NextApiRequest, NextApiResponse } from 'next';
import mongoose from 'mongoose';
import User from '../../../models/User';
// 连接 MongoDB(仅在未连接时连接)
const connectDB = async () => {
if (mongoose.connections[0].readyState) return;
await mongoose.connect(process.env.MONGODB_URI);
};
export default async function handler(req, res) {
await connectDB();
switch (req.method) {
case 'GET':
// 获取所有用户
try {
const users = await User.find({});
res.status(200).json(users);
} catch (error) {
res.status(500).json({ error: '获取用户失败' });
}
break;
case 'POST':
// 创建新用户
try {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: '缺少 name 或 email' });
}
const newUser = await User.create({ name, email });
res.status(201).json(newUser);
} catch (error) {
if (error.code === 11000) {
res.status(400).json({ error: '邮箱已存在' });
} else {
res.status(500).json({ error: '创建用户失败' });
}
}
break;
default:
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`方法 ${req.method} 不允许`);
}
}
五、配置环境变量
在项目根目录创建 .env.local
文件:
env
# .env.local
MONGODB_URI=mongodb+srv://你的用户名:你的密码@cluster0.xxxxx.mongodb.net/nextapi?retryWrites=true&w=majority
🔒 注意 :
.env.local
会被 Git 忽略,确保敏感信息不泄露!
六、测试接口
1. 启动项目
bash
npm run dev
2. 测试 POST(创建用户)
使用 Postman 或 curl:
bash
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name":"张三","email":"zhangsan@example.com"}'
✅ 返回:
json
{ "_id": "xxx", "name": "张三", "email": "zhangsan@example.com", "createdAt": "2024-06-01T00:00:00.000Z" }
3. 测试 GET(获取所有用户)
bash
curl http://localhost:3000/api/users
✅ 返回用户列表数组。
七、部署到 Vercel(免费!)
- 将代码推送到 GitHub;
- 登录 Vercel,导入项目;
- 在 Environment Variables 中添加
MONGODB_URI
; - 点击 Deploy!
🚀 部署完成后,你的 API 接口就变成真实线上接口了!
例如:
https://next-api-demo.vercel.app/api/users
Vercel是一个专注于前端和全栈应用部署的云端平台,由Zeit公司开发。它以零配置部署、全球CDN加速和对主流框架的深度支持为核心优势,成为开发者快速上线项目的首选工具。无论是个人博客、企业官网,还是复杂的应用程序,Vercel都能提供高效、稳定且低成本的解决方案
八、注意事项 & 最佳实践
问题 | 建议 |
---|---|
数据库连接频繁 | 使用单例模式(如上文 connectDB )避免重复连接 |
CORS 问题 | Vercel 默认允许所有来源,本地开发可用 next dev 无跨域 |
安全性 | 生产环境务必校验参数、防注入、限制请求频率 |
扩展性 | 复杂业务建议拆分为多个文件(如 users/[id].js ) |
九、结语
通过 Next.js 的 API 路由,前端开发者也能轻松写出后端接口 ,无需额外学习 Express 或搭建服务器。配合 MongoDB,你可以在一个项目中完成完整的 CRUD 功能,快速验证想法、开发 MVP。
💡 适合场景:个人项目、博客后台、小型管理系统、原型验证。