0Pricing
Next.js 15 Fullstack Web Apps · 课时

构建 API 路由处理程序

使用 App Router 的路由处理程序创建健壮的 RESTful API 端点,实现后端逻辑。

构建 API 路由处理程序 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Welcome to Route Handlers

In Next.js 15, Route Handlers are the powerful way to build backend API endpoints directly within your App Router project.

They allow you to create RESTful APIs, handle webhooks, or perform any server-side logic, all co-located with your frontend code.

Why Use Route Handlers?

Route Handlers offer several benefits:

  • Simplicity: No need for a separate backend server.
  • Co-location: API logic lives next to related UI components.
  • Performance: Built on Web Standard APIs, making them efficient.
  • Flexibility: Support all HTTP methods (GET, POST, PUT, DELETE, etc.).

Creating Your First Handler

To create a Route Handler, define a route.ts (or .js) file inside an app directory segment. For example, app/api/hello/route.ts will handle requests to /api/hello.

Inside this file, you export functions that match HTTP methods, like GET, POST, etc.

Handling GET Requests

The GET function handles HTTP GET requests. It receives a NextRequest object and should return a NextResponse.

Let's create a simple 'hello world' API endpoint.

import { NextResponse } from 'next/server';

export async function GET() {
  return NextResponse.json({ message: 'Hello from API!' });
}

How to Access GET Handler

The previous code snippet, placed in app/api/hello/route.ts, creates an endpoint accessible at /api/hello.

When you navigate to http://localhost:3000/api/hello in your browser, you'll see the JSON response: {"message":"Hello from API!"}.

Handling POST Requests

For data submission, you'll use the POST function. It also receives the NextRequest object, which contains the request body.

You can parse the JSON body using await request.json().

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

export async function POST(request: NextRequest) {
  const data = await request.json();
  return NextResponse.json(
    { message: 'Data received', data },
    { status: 200 }
  );
}

Accessing Request Details

The NextRequest object provides rich access to request details:

  • request.url: The full request URL.
  • request.headers: Request headers (e.g., request.headers.get('Content-Type')).
  • request.nextUrl.searchParams: Query parameters (e.g., ?name=Alice).

These are crucial for dynamic and secure API logic.

Dynamic Segments in Handlers

Just like pages, Route Handlers can have dynamic segments. For example, app/api/items/[id]/route.ts.

You can access these dynamic parameters from the params object passed to your handler function.

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

interface Params {
  params: { id: string };
}

export async function GET(
  request: NextRequest,
  { params }: Params
) {
  const id = params.id; // '123' for /api/items/123
  return NextResponse.json({ itemId: id, message: 'Fetched item' });
}

Setting Status and Headers

When returning a NextResponse, you can customize the HTTP status code and headers.

This is important for proper API communication, like indicating success (200, 201) or errors (400, 404, 500).

import { NextResponse } from 'next/server';

export async function DELETE() {
  return new NextResponse(null, { status: 204 }); // No Content
}

Quick Check: Handler Basics

You want to create an API endpoint at /api/products that returns a list of products when a GET request is made.

Which code snippet correctly sets up this handler in app/api/products/route.ts?

Recap: Building API Handlers

You've learned the fundamentals of Next.js 15 Route Handlers!

  • They allow backend logic co-located in the app directory.
  • Define handlers by exporting functions (GET, POST, etc.) in a route.ts file.
  • Use NextRequest to access request details and NextResponse to send responses.
  • Dynamic segments enable flexible API routes.

This powerful feature streamlines fullstack development in Next.js.

常见问题解答

「构建 API 路由处理程序」课时是免费的吗?

是的 — 「构建 API 路由处理程序」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

「构建 API 路由处理程序」这节课中我会学到什么?

使用 App Router 的路由处理程序创建健壮的 RESTful API 端点,实现后端逻辑。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack Web Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「构建 API 路由处理程序」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 构建 API 路由处理程序
  2. 请求验证与安全
  3. 集成外部服务
  4. 速率限制与 API 错误处理
← 返回 Next.js 15 Fullstack Web Apps