Skip to content

处理请求

REST 示例

GET

ts
/* 
  GET http://localhost:3000/api/comments?keyword=xxx
 */
export async function GET(request: NextRequest) {
  const search = request.nextUrl.searchParams
  const keyword = search.get('keyword')

  const newComments = comments.filter((c) => c.text.includes(keyword))

  return Response.json(newComments)
}
ts
/* 
  GET http://localhost:3000/api/comments/:id
 */
export async function GET(request: NextRequest, ctx: { params: { id: string } }) {
  const params = ctx.params

  const { id } = params
  const newComments = comments.find((c) => c.id === Number(id))

  return Response.json(newComments)
}

POST

ts
/* 
  POST http://localhost:3000/api/comments
  body: { "text": "New Data" }
*/
export async function POST(request: NextRequest) {
  const body = await request.json()

  const newComment = {
    id: comments.length + 1,
    text: body.text,
  }
  comments.push(newComment)

  return new Response(JSON.stringify(comments), {
    headers: { 'Content-Type': 'application/json' },
    status: 201,
  })
}

PUT

ts
/* 
  PUT http://localhost:3000/api/comments/:id
  body: { "text": "Updated Data" }
*/
export async function PUT(request: NextRequest, ctx: { params: { id: string } }) {
  const params = ctx.params
  const body = await request.json()

  const { id } = params
  const newComments = comments.map((e) => {
    if (e.id === Number(id)) {
      e.text = body.text
    }
    return e
  })

  return new Response(JSON.stringify(newComments), {
    headers: { 'Content-Type': 'application/json' },
    status: 200,
  })
}

DELETE

ts
export async function DELETE(request: Request, ctx: { params: { id: string } }) {
  const params = ctx.params

  const { id } = params
  const index = comments.findIndex((c) => c.id === Number(id))
  const deleteComment = comments[index]
  comments.splice(index, 1)

  return new Response(JSON.stringify(deleteComment), {
    headers: { 'Content-Type': 'application/json' },
    status: 200,
  })
}

重定向

ts
import { redirect } from 'next/navigation'

// ...
redirect('/comments')
redirect('https://jsonplaceholder.typicode.com/posts')
// ...

接收参数

获取 Query 参数

ts
/* 
  GET http://localhost:3000/api/comments?keyword=xxx
 */
export async function GET(request: NextRequest) {
  const search = request.nextUrl.searchParams
  console.log('@search', search)

  const keyword = search.get('name')
  console.log(keyword)
  // ...
}

或者

ts
/* 
  GET http://localhost:3000/api/comments?keyword=xxx
 */
export async function GET(request: Request) {
  const search = new URL(request.url).searchParams
  console.log('@search', search)

  const keyword = search.get('name')
  console.log(keyword)
  // ...
}

获取 Path 参数

ts
/* 
  GET http://localhost:3000/api/comments/1
 */
export async function GET(request: NextRequest, ctx: { params: { id: string } }) {
  const params = ctx.params
  console.log('@params', params)

  const { id } = params
  console.log(id)
  // ...
}

获取 Body

ts
/* 
  POST http://localhost:3000/api/comments
  body: { "text": "New Data" }
*/
export async function POST(request: NextRequest) {
  const body = await request.json()
  console.log('@body', body)
  // ...
}

获取 Headers

ts
import { headers } from 'next/headers'

export async function GET(request: NextRequest) {
  const requestHeaders = request.headers
  const headerList = headers()

  console.log(requestHeaders.get('Authorization'))
  console.log(headerList.get('Authorization'))
  // ...
}

获取 Cookies

ts
import { cookies } from 'next/headers'

export async function GET(request: NextRequest) {
  console.log(request.cookies.get('Authorization'))
  console.log(cookies().get('Authorization'))
  // ...
}

响应数据

设置数据(JSON 为例)

ts
return new Response(JSON.stringify(data), {
  headers: { 'Content-Type': 'application/json' },
  status: 200,
})

或者

ts
return Response.json(data)

设置 Headers

ts
return new Response(JSON.stringify(data), {
  headers: {
    'Content-Type': 'application/json',
    'x-custom-header': 'my value',
  },
  status: 200,
})

设置 Cookies

ts
return new Response(JSON.stringify(data), {
  headers: {
    'Content-Type': 'application/json',
    'Set-Cookie': 'name=value; HttpOnly; Path=/; Max-Age=86400', // 1 day
  },
  status: 200,
})

或者

ts
import { cookies } from 'next/headers'

const cookieStore = cookies()
cookieStore.set('name', 'value')

基于 MIT 许可发布