并行路由
同一個頁面,放多個路由,,
目錄前面加@,layout中可以當作插槽引入
import React from "react";function layout({children,notifications,user}:{children:React.ReactNode,notifications:React.ReactNode,user:React.ReactNode
}){return (<div>layout{notifications}<div>{user}</div></div>)
}export default layout
nextjs攔截跳轉頁面
next寫接口
創建route.ts
,
export async function POST(request:Request){var 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})
}
next接收queryParams
import {type NextRequest} from "next/server"
export async function GET(request:NextRequest,){var searchParams = request.nextUrl.searchParams;var query = searchParams.get("query");var find = query?comments.find(comment=>comment.text.includes(query)):comments;return Response.json(find)
}
獲取請求頭
- 第一種
import {type NextRequest} from "next/server"
export async function GET(request:NextRequest,){var requestHeaders = new Headers(request.headers);console.log(requestHeaders.get("Authorization"))}
- 第二種
import {type NextRequest} from "next/server"
import {headers} from "next/headers"
export async function GET(request:NextRequest,){const headersList = await headers()console.log(headersList.get("Authorization"))return Response.json("xxx")
}
獲取cookie
兩種方式獲取cookie
middleware中間件攔截
middleware.ts
跟app一個層級
import type {NextRequest} from "next/server";
import {NextResponse} from "next/server"export function middleware(request:NextRequest){console.log(request.nextUrl.pathname,"pathname")// 重定向: 地址會變 // return NextResponse.redirect(new URL("/",request.url))// 轉發,, 瀏覽器url不變,內容變化return NextResponse.rewrite(new URL("/",request.url))
}export const config = {// 將 /hello 轉發到 / matcher:"/hello"
}
中間件處理response:===> 設置cookie或者響應頭
import type {NextRequest} from "next/server";
import {NextResponse} from "next/server"export function middleware(request:NextRequest){console.log(request.nextUrl.pathname,"pathname")var response = NextResponse.next();var themePreference = request.cookies.get("theme");if (!themePreference){response.cookies.set("theme","dark")}return response
}export const config = {// 將 /hello 轉發到 /matcher:"/hello"
}