Skip to content

Next.js - 响应辅助函数

Next.js - Route Handler 响应助手方法

Section titled “Next.js - Route Handler 响应助手方法”

在 Next.js App Router 中,API 端点是通过 Route Handlers 创建的(app 目录内名为 route.js 或 route.ts 的文件)。Route Handlers 使用标准的 Web API Request 和 Response 对象,以及 Next.js 的扩展,如 NextResponse,而不是 Node.js 或 Express 中传统的 req 和 res 对象。

NextResponse 对象提供了方便的助手方法来构建响应。

  • NextResponse.json(body, init?): 发送 JSON 响应。自动设置 Content-Type 头部为 application/json。body 必须是一个可序列化的对象。init 是一个可选对象,用于设置状态码、头部等(例如,{ status: 201, headers: { 'X-Custom-Header': 'value' } })。
  • NextResponse.redirect(url, status?): 发送重定向响应到指定的 URL。默认状态码是 307(临时重定向),但你可以指定其他状态码,如 301(永久)或 308。
  • NextResponse.next(): 主要用于 Middleware 中,以继续处理请求。
  • (Standard Response): 你也可以返回一个标准的 Response 对象以获得更多控制(例如,new Response('Hello World', { status: 200 }))。

让我们创建一个示例 Route Handler,演示常见的响应类型。

创建 app/api/users/route.ts 文件,内容如下:

app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
interface User {
id: number;
name: string;
email: string;
}
// In-memory 'database' for demonstration
// 用于演示的内存“数据库”
const users: User[] = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
];
// Handler for GET requests
// GET 请求处理函数
export async function GET(request: NextRequest) {
// Example: Get query parameter
// 示例:获取查询参数
const searchParams = request.nextUrl.searchParams;
const userId = searchParams.get('id');
if (userId) {
const user = users.find(u => u.id === parseInt(userId));
if (user) {
// Return specific user as JSON
// 返回特定用户的 JSON
return NextResponse.json(user);
} else {
// Return 404 Not Found with a JSON message
// 返回 404 Not Found 状态及 JSON 消息
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
}
// Return all users as JSON
// 返回所有用户的 JSON
return NextResponse.json(users);
}
// Handler for POST requests
// POST 请求处理函数
export async function POST(request: NextRequest) {
try {
const newUser: Omit<User, 'id'> = await request.json(); // Parse JSON body
// 解析 JSON 请求体
if (!newUser.name || !newUser.email) {
return NextResponse.json({ error: 'Missing name or email' }, { status: 400 }); // Bad Request
// 返回 400 Bad Request(请求错误)
}
const createdUser: User = {
id: Math.max(0, ...users.map(u => u.id)) + 1, // Simple ID generation
// 简单的 ID 生成
...newUser,
};
users.push(createdUser);
// Return the created user with status 201 Created
// 返回创建成功的用户,状态码 201 Created(已创建)
return NextResponse.json(createdUser, { status: 201 });
} catch (error) {
// Handle potential JSON parsing errors
// 处理潜在的 JSON 解析错误
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
}
}

如果开发服务器未运行,请运行它:

npm run dev
  1. GET 所有用户: 在浏览器中访问 http://localhost:3000/api/users,或使用 curl、Postman 等工具。你应该会看到包含用户信息的 JSON 数组,状态码为 200 OK。
// Expected Output for GET /api/users
// GET /api/users 的预期输出
[
{ "id": 1, "name": "Alice", "email": "alice@example.com" },
{ "id": 2, "name": "Bob", "email": "bob@example.com" }
]
  1. GET 特定用户: 访问 http://localhost:3000/api/users?id=1。你应该会看到 Alice 的 JSON 对象。
// Expected Output for GET /api/users?id=1
// GET /api/users?id=1 的预期输出
{ "id": 1, "name": "Alice", "email": "alice@example.com" }
  1. GET 不存在的用户: 访问 http://localhost:3000/api/users?id=99。你应该会收到 404 Not Found 状态码以及 JSON 错误信息。
// Expected Output for GET /api/users?id=99
// GET /api/users?id=99 的预期输出
{ "error": "User not found" }
  1. POST 新用户 (使用 curl):
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name": "Charlie", "email": "charlie@example.com"}'

你应该会收到 201 Created 状态码以及新创建用户的 JSON 数据(id 为 3)。

// Expected Output for POST /api/users
// POST /api/users 的预期输出
{ "id": 3, "name": "Charlie", "email": "charlie@example.com" }