== 서버 사이드 API 엔드포인트를 생성할 수 있는 기능
- HTTP Mehod를 처리하는 서버 기능 == Serverless
- Server Actions 방법이 나오기 전 방법
<방법>
- app/~~/route.ts
- API Route라고 NextJS의 특수한 파일
- 파일구조(~~)가 api 주소가 된다
- 해당 파일에 GET / POST / PUT / DELETE 함수 생성(대문자로) - 핸들러
- api를 메소드와 함께 요청하면 알아서 각 메소드 함수로 보냄
- NextRequest 타입의 request 객체를 props로
- 사용자의 cookie, ip, 위치정보, 현재 url, 이동할 url을 제공
- 요청을 객체화 : request.json()
객체를 json 형태로 : Response.json(객체)
export async function GET(request: NextRequest) { console.log(request); return Response.json({ ok: true, }); } export async function POST(request: NextRequest) { const data = await request.json(); console.log("POST~"); return Response.json(data); }
<사용>
- api 호출은 기존처럼 fetch 함수 등으로 하면 됨
const onClick = async () => { await fetch("api/users/", { method: "POST", body: JSON.stringify({ username: "쿵치", password: "1234", }), }); };
- RN, Webhook 등에서는 여전히 이 방법을 사용해야함