并行路由
同一个页面,放多个路由,,
目录前面加@,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"
}