next.js 以其服务器端渲染和静态站点生成功能而闻名,但它还允许您使用服务器端功能(包括 api)构建成熟的应用程序。使用 next.js,您可以直接在框架本身内轻松创建 rest api,它可以由您的前端应用程序或任何外部服务使用。
在这篇博文中,我们将介绍如何在 next.js 中创建简单的 rest api 以及如何在应用程序内和外部使用该 api。最后,您将深入了解如何在 next.js 项目中构建 api 并与之交互。
在 next.js 中创建 rest api
next.js 提供了一种使用 pages/api 目录构建 api 路由的简单方法。您在此目录中创建的每个文件都会自动成为 api 端点,其中文件名对应于端点的路由。
第 1 步:设置新的 next.js 项目
如果您还没有 next.js 项目,您可以通过运行以下命令轻松创建一个项目:
npx create-next-app my-next-api-project cd my-next-api-project npm install mongodb npm run dev
这将创建一个基本的 next.js 应用程序并启动开发服务器。您现在可以开始构建 rest api。
第 2 步:创建您的 api 路由
在 next.js 中,api 路由是在 pages/api 文件夹中创建的。例如,如果您想创建一个简单的 api 来管理用户,您可以在 pages/api 目录中创建一个名为 users.js 的文件。
mkdir pages/api touch pages/api/users.js
在users.js中,您可以定义api路由。这是一个使用用户列表进行响应的简单示例:
// pages/api/users.js
export default function handler(req, res) {
// define a list of users
const users = [
{ id: 1, name: "john doe", email: "john@example.com" },
{ id: 2, name: "jane smith", email: "jane@example.com" },
];
// send the list of users as a json response
res.status(200).json(users);
}
第 3 步:创建 mongodb 连接实用程序
为了确保您不会为每个 api 请求打开新的数据库连接,最好创建一个可重用的 mongodb 连接实用程序。您可以通过创建 lib/mongodb.js 文件来完成此操作,该文件处理与 mongodb 实例的连接并重用该连接。
这是一个简单的 mongodb 连接实用程序的示例:
// lib/mongodb.js
import { mongoclient } from 'mongodb';
const client = new mongoclient(process.env.mongodb_uri, {
usenewurlparser: true,
useunifiedtopology: true,
});
let clientpromise;
if (process.env.node_env === 'development') {
// in development, use a global variable so the mongodb client is not re-created on every reload
if (global._mongoclientpromise) {
clientpromise = global._mongoclientpromise;
} else {
global._mongoclientpromise = client.connect();
clientpromise = global._mongoclientpromise;
}
} else {
// in production, it’s safe to use the mongoclient directly
clientpromise = client.connect();
}
export default clientpromise;
第 4 步:在 .env.local 中设置 mongodb uri
要安全地存储 mongodb uri,请在项目的根目录中创建一个 .env.local 文件。在此处添加您的 mongodb uri:
# .env.local mongodb_uri=mongodb+srv://: @cluster0.mongodb.net/mydatabase?retrywrites=true&w=majority
如果您使用 mongodb atlas,您可以从 atlas 仪表板获取此 uri。
第 5 步:创建与 mongodb 交互的 api 路由
您可以通过检查 req.method 属性来处理 api 中的不同 http 方法(get、post、put、delete)。这是 users.js 文件的更新版本,它根据 http 方法做出不同的响应。
// pages/api/users.js
import clientpromise from '../../lib/mongodb';
export default async function handler(req, res) {
const client = await clientpromise;
const db = client.db(); // connect to the default database (replace with your db name if needed)
const userscollection = db.collection('users'); // 'users' collection in mongodb
switch (req.method) {
case 'get':
// retrieve all users
try {
const users = await userscollection.find({}).toarray();
res.status(200).json(users);
} catch (error) {
res.status(500).json({ message: 'error fetching users' });
}
break;
case 'post':
// add a new user
try {
const { name, email } = req.body;
const newuser = await userscollection.insertone({ name, email });
res.status(201).json(newuser.ops[0]);
} catch (error) {
res.status(500).json({ message: 'error creating user' });
}
break;
case 'put':
// update an existing user by id
try {
const { id, name, email } = req.body;
const updateduser = await userscollection.updateone(
{ _id: new objectid(id) },
{ $set: { name, email } }
);
res.status(200).json(updateduser);
} catch (error) {
res.status(500).json({ message: 'error updating user' });
}
break;
case 'delete':
// delete a user by id
try {
const { id } = req.body;
await userscollection.deleteone({ _id: new objectid(id) });
res.status(200).json({ message: 'user deleted' });
} catch (error) {
res.status(500).json({ message: 'error deleting user' });
}
break;
default:
res.status(405).json({ message: 'method not allowed' });
break;
}
}
现在,您的 api 能够处理 get、post、put 和 delete 请求来管理用户。
- get 获取所有用户。
- post 添加新用户。
- put 更新现有用户。
- delete 删除用户。
第 6 步:测试 api
现在您已经设置了 api,您可以通过使用 postman 或 curl 等工具发出请求来测试它。以下是每种方法的 url:
- 向 /api/users 发出 get 请求以检索用户列表。
- 向 /api/users 发送 post 请求以创建新用户(在请求正文中发送用户数据)。
- 向 /api/users 发出 put 请求以更新现有用户(在请求正文中发送用户数据)。
- 向 /api/users 发送 delete 请求以删除用户(在请求正文中发送用户 id)。
第 5 步:保护您的 api(可选)
您可能希望向 api 添加一些基本身份验证或授权,以防止未经授权的访问。您可以通过检查 req.headers 或使用环境变量来存储 api 密钥来轻松完成此操作。例如:
Sylius开源电子商务平台是一个开源的 PHP 电子商务网站框架,基于 Symfony 和 Doctrine 构建,为用户量身定制解决方案。可管理任意复杂的产品和分类,每个产品可以设置不同的税率,支持多种配送方法,集成 Omnipay 在线支付。功能特点:前后端分离Sylius 带有一个强大的 REST API,可以自定义并与您选择的前端或您的微服务架构很好地配合使用。如果您是 Symfony
export default function handler(req, res) {
const apikey = req.headers['api-key'];
if (apikey !== process.env.api_key) {
return res.status(403).json({ message: 'forbidden' });
}
// continue with the request handling as usual
}
在 next.js 应用程序中使用 rest api
现在您已经设置了 api,让我们看看如何在 next.js 应用程序中使用它。使用 api 的方法有多种,但最常见的方法是使用 fetch(或 axios 等库)发出 http 请求。
第 1 步:使用 getserversideprops 获取数据
如果您需要从服务器端的 api 获取数据,可以使用 next.js 的 getserversideprops 在渲染页面之前获取数据。以下是如何在页面组件内使用 /api/users 端点的示例:
// pages/users.js
export async function getserversideprops() {
const res = await fetch('http://localhost:3000/api/users');
const users = await res.json();
return { props: { users } };
}
export default function userspage({ users }) {
return (
users
{users.map(user => (
-
{user.name} - {user.email}
))}
);
}
在此示例中,当用户访问 /users 页面时,getserversideprops 将在渲染页面之前从 api 获取用户列表。这确保了页面加载时数据已经可用。
第 2 步:使用 useeffect 获取客户端数据
您还可以使用 react 的 useeffect 钩子来使用 api 客户端。这对于在页面加载后获取数据很有用。
// pages/users.js
import { usestate, useeffect } from 'react';
export default function userspage() {
const [users, setusers] = usestate([]);
useeffect(() => {
const fetchusers = async () => {
const res = await fetch('/api/users');
const data = await res.json();
setusers(data);
};
fetchusers();
}, []);
return (
users
{users.map(user => (
-
{user.name} - {user.email}
))}
);
}
在此示例中,api 请求是在组件安装后发出的,并且用户列表在组件的状态中更新。
步骤 3:发出 post 请求以添加数据
要将数据发送到您的 api,您可以使用 post 请求。以下是如何将新用户的数据发送到 /api/users 端点的示例:
import { useState } from 'react';
export default function CreateUser() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleSubmit = async (event) => {
event.preventDefault();
const newUser = { name, email };
const res = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newUser),
});
if (res.ok) {
alert('User created successfully!');
}
};
return (
);
}
在此示例中,新用户的姓名和电子邮件作为 post 请求发送到 api。请求成功后,会显示警报。
结论
next.js 让直接在同一框架内构建和使用 rest api 变得异常简单。通过使用 api 路由 功能,您可以创建可以处理 crud 操作并将其与前端无缝集成的无服务器端点。
在这篇文章中,我们介绍了如何在 next.js 中创建 rest api、处理不同的 http 方法,以及如何在服务器端(使用 getserversideprops)和客户端(使用 useeffect)使用该 api。这为以最少的配置构建全栈应用程序提供了多种可能性。
next.js 继续为开发人员提供灵活而简单的解决方案,用于构建具有集成后端功能的可扩展应用程序。快乐编码!









