【Next.js 入门教程系列】04-构造 API

原文链接

CSDN 的排版/样式可能有问题,去我的博客查看原文系列吧,觉得有用的话, 给我的点个star,关注一下吧

上一篇【Next.js 入门教程系列】03-路由与跳转

构造 API

本篇包括以下内容:

  • Getting objects
  • Creating objects
  • Updating objects
  • Deleting objects
  • Validating requests with Zod

获取对象

本章代码链接

我们可以创建 route.tsx 来创建一个 GET API,注意与 page.tsx 不能同时存在于一个文件夹内,一般约定俗成在 app\api 文件夹下创建各种 API 接口。其需要一个 NextRequest 类型的参数,下面是一个示例

import { NextRequest, NextResponse } from "next/server";

export function GET(request: NextRequest) {
  return NextResponse.json([
    { id: 1, name: "Castamere" },
    { id: 2, name: "Today_Red" },
  ]);
}

除此之外,我们也可以应用之前的动态路由,来根据 id 等数据查询数据并获取。可以在该文件夹下创建 [id] 文件夹,添加 route.tsx 来获取参数

import { NextRequest, NextResponse } from "next/server";

export function GET(
  request: NextRequest,
  //   直接使用params 结构,因为api中一般不会有过多参数,如有,可以额外定义interface
  { params: { id } }: { params: { id: number } }
) {
  if (id > 10)
    return NextResponse.json({ error: "User not found" }, { status: 404 });
  return NextResponse.json({ id, name: "Castamere" });
}

创建对象

本章代码链接

创建对象时我们可以使用 POST API,输入仍为一个 NextRequest 类型的参数。注意 POST 一般需要获取收到的数据,要设为 async 函数,其中的 request.json() 在获取时要使用 await 关键字

export async function POST(request: NextRequest) {
  const body = await request.json();
  if (!body.name)
    return NextResponse.json({ error: "Name is required" }, { status: 400 });
  return NextResponse.json({ id: 1, name: body.name }, { status: 201 });
}

在测试 API 时,我们可以使用Postman

更新对象

本章代码链接

更新对象时,可以使用 PUT 或者 PATCH。他们的区别是,PUT 一般用于直接替换某个对象,而 PATCH 用于更新某些属性。同样的,要用到 request body 的情况下都要将函数设为 async

// Use put for replacing
// Use patch for updating some properties
export async function PUT(
  request: NextRequest,
  { params: { id } }: { params: { id: number } }
) {
  // Validate the request body
  const body = await request.json();
  // If invalid, return 400
  if (!body.name)
    return NextResponse.json({ error: "Name is required" }, { status: 400 });
  // Fetch the user
  // If does not exist, return 404
  if (id > 10)
    return NextResponse.json({ error: "User not found" }, { status: 404 });
  // Update the user
  // Return the updated user
  return NextResponse.json({ id, name: body.name });
}

删除对象

本章代码链接

删除对象时,使用 DELETE。

export function DELETE(
  request: NextRequest,
  { params: { id } }: { params: { id: number } }
) {
  // Fetch user from db
  // If does not exist, return 404
  if (id > 10)
    return NextResponse.json({ error: "User not found" }, { status: 404 });
  // Delete the user
  // Return 200
  return NextResponse.json({});
}

使用 Zod 验证表单

本章代码链接

Zod可以直接使用 npm i zod 安装。安装好后,创建 schema.ts 来创建一个表单的格式 interface

import { z } from "zod";

const schema = z.object({
  name: z.string().min(3),
});

export default schema;

然后在 tsx 文件中导入,使用 schema.safeParse() 即可进行表单格式的验证

import schema from "./schema";

export async function POST(request: NextRequest) {
  const body = await request.json();
  //   使用 zod 来验证
  const validation = schema.safeParse(body);
  if (!validation.success)
    return NextResponse.json(validation.error.errors, { status: 400 });
  return NextResponse.json({ id: 1, name: body.name }, { status: 201 });
}

CSDN 的排版/样式可能有问题,去我的博客查看原文系列吧,觉得有用的话, 给我的点个star,关注一下吧

下一篇讲数据库 

下一篇 【Next.js 入门教程系列】05-数据库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值