文章
next js Routing 学习笔记 03
route.tsx
/comments/data.ts
export const comments = [
{
id: 1,
text: "This is the first comment",
},
{
id: 2,
text: "This is the second comment",
},
{
id: 3,
text: "This is the third comment",
},
];
/comments/route.ts
import { NextRequest } from "next/server";
import { comments } from "./data";
// export async function GET() {
// return Response.json(comments);
// }
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const query = searchParams.get("query");
const filteredComments = query
? comments.filter((comment) => comment.text.includes(query))
: comments;
return Response.json(filteredComments);
}
export async function POST(request: Request) {
const comment = await request.json();
const newComment = { id: comments.length + 1, text: comment.text };
comments.push(newComment);
return new Response(JSON.stringify(newComment), {
headers: { "Content-Type": "application/json" },
status: 201,
});
}
动态路由处理
/comments/[id]/route.ts
import { comments } from "../data";
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const comment = comments.find((comment) => comment.id === parseInt(id));
return Response.json(comment);
}
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const body = await request.json();
const { text } = body;
const index = comments.findIndex((comment) => comment.id === parseInt(id));
comments[index].text = text;
return Response.json(comments[index]);
}
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const index = comments.findIndex((comment) => comment.id === parseInt(id));
const deletedComment = comments[index];
comments.splice(index, 1);
return Response.json(deletedComment);
}
Headers
- RequestHeaders
- ResponseHeaders
import { type NextRequest } from "next/server";
import { headers } from "next/headers";
import { cookies } from "next/headers";
export async function GET(request: NextRequest) {
const requestHeaders = new Headers(request.headers);
console.log(requestHeaders.get("Authorization"));
const headersList = await headers();
console.log(headersList.get("Authorization"));
const theme = request.cookies.get("theme");
console.log(theme);
const cookieStore = await cookies();
cookieStore.set("resultsPerPage", "20");
console.log(cookieStore.get("resultsPerPage"));
return new Response("<h1>Profile API data</h1>", {
headers: {
"Content-Type": "text/html",
"Set-Cookie": `theme=dark`,
},
});
}
route handlers 缓存
仅适用于GET请求
Middleware 中间件
路径:/src/middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const response = NextResponse.next()
const themePreference = request.cookies.get("theme")
if (!themePreference) {
response.cookies.set("theme", "dark")
}
response.headers.set("custom-header", "custom-value")
return response
// return NextResponse.redirect(new URL("/", request.url))
// if (request.nextUrl.pathname === "/profile") {
// console.log("url: ", request.url)
// console.log("nextUrl: ", request.nextUrl)
// return NextResponse.redirect(new URL("/hello", request.nextUrl))
// }
}
// export const config = {
// matcher: "/profile"
// }