NextResponse
NextResponse 扩展了 Web Response API
new NextResponse()
new NextResponse(body, options) 构造函数创建了一个新的 Response 对象。 body 可以是:
- Blob
- Buffer
- FormData
- ReadableStream
- URLSearchParams
- String
import { NextResponse } from 'next/server'
export function middleware(request: NextRequest) {
return new NextResponse('Hello world', {status: 200})
}
NextResponse.json()
返回json格式的响应
import { NextResponse } from 'next/server'
export async function middleware(request) {
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}
NextResponse.redirect()
重定向到指定url
import { NextResponse } from 'next/server'
export async function middleware(request) {
return NextResponse.redirect(new URL('/new', request.url))
}
NextResponse.rewrite()
重写请求
import { NextResponse } from 'next/server'
import { NextResponse } from 'next/server'
export async function middleware(request) {
return NextResponse.rewrite(new URL('/proxy', request.url))
}
NextResponse.next()
继续执行下一个中间件,同时返回响应
import { NextResponse } from 'next/server'
export async function GET(request) {
const response = NextResponse.next()
response.cookies.set('show-banner', 'false')
return response;
}