파피루스

[nextJs/react] 매번 헷갈리는 파라미터 가져오기 본문

React

[nextJs/react] 매번 헷갈리는 파라미터 가져오기

떼굴펜 2024. 9. 5. 18:46

Next Client Component = React 

const { name } = useParams();

 

Next Server component

type PageProps = {
  params: { slug: string }
  searchParams: { [key: string]: string | string[] | undefined }
};

export default function Page({  params,  searchParams } : PageProps ) {
  return <h1>My Page</h1>
}

 

 

Next app router

1. GET

import { type NextRequest } from 'next/server'
 
export function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const query = searchParams.get('query')
  // query is "hello" for /api/search?query=hello
}

 

2. POST (Get 외에는 다 요 방식 쓰면 됨) 

2-1. POST request body

export async function POST(request: Request) {
  const res = await request.json()
  return Response.json({ res })
}

 

2-1. POST formData

export async function POST(request: Request) {
  const formData = await request.formData()
  const name = formData.get('name')
  const email = formData.get('email')
  return Response.json({ name, email })
}

 

 

 

 

참고 링크

- https://nextjs.org/docs/app/building-your-application/routing/route-handlers

- https://nextjs.org/docs/app/api-reference/file-conventions/page