从0死磕全栈之Next.js API 路由实战:不用后端,前端也能写接口!

摘要 :还在为前后端联调烦恼?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.jshttp://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(创建用户)

使用 Postmancurl

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(免费!)

  1. 将代码推送到 GitHub;
  2. 登录 Vercel,导入项目;
  3. Environment Variables 中添加 MONGODB_URI
  4. 点击 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。

💡 适合场景:个人项目、博客后台、小型管理系统、原型验证。

相关推荐
90后的晨仔2 小时前
Vue 插槽(Slots)全面解析与实战指南
前端·vue.js
Nathan202406162 小时前
Kotlin-Sealed与Open的使用
android·前端·面试
MQliferecord2 小时前
前端性能优化实践经验总结
前端
RoyLin3 小时前
SurrealDB - 统一数据基础设施
前端·后端·typescript
longlongago~~3 小时前
富文本编辑器Tinymce的使用、行内富文本编辑器工具栏自定义class、katex渲染数学公式
前端·javascript·vue.js
2501_915921433 小时前
前端用什么开发工具?常用前端开发工具推荐与不同阶段的选择指南
android·前端·ios·小程序·uni-app·iphone·webview
aixfe3 小时前
BiomeJS 2.0 忽略目录配置方法
前端
Mintopia3 小时前
Cesium-kit 又发新玩意儿了:CameraControl 相机控制组件全解析
前端·three.js·cesium
ssshooter3 小时前
shader更换后,数据需要重新加载吗?
前端