FrontEngineer JungBam

api Router 본문

next.js

api Router

정밤톨 2023. 7. 27. 11:56

 

 

 가장 눈에 띄게 바뀐 부분은 바로 각각의 메쏘드에 따른 처리방식이다.

 기존에 request로 들어온 method를 비교해서 처리하던 방식에서 node나 express에서의 라우터 처리방식처럼 get, post, put, patch, delete에 대하여 각각 다른 함수 내에서 처리되도록 변경되었다.(아래 공식문서 예제 코드 참고) 

import { NextResponse } from 'next/server'
 
export async function GET() {
  const res = await fetch('https://data.mongodb-api.com/...', {
    headers: {
      'Content-Type': 'application/json',
      'API-Key': process.env.DATA_API_KEY,
    },
  })
  const data = await res.json()
 
  return NextResponse.json({ data })
}

 사실 너무 간단하게 구현이 가능하기 때문에 다른 설명이 필요없을 정도...

 

 서버 작업을 조금이라도 해보셨던 분들이라면 모든 처리가 눈에 익고 어렵지 않을 것 같다.
 당연히 COR 처리, redirect와 같이 서버에서 처리하는 각각의 기능도 간단하게 구현 가능한데, 공식문서 예제를 통해 살펴보자.

export async function GET(request: Request) {
  return new Response('Hello, Next.js!', {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    },
  })
}

 서버에서 처리해주는 것과 같이 header에 access-control-allow 속성을 통해 처리가 가능하다.

 Access-Allow 관련된 것은 아래 Mozila에서 확인해보자.

 

Access-Control-Allow-Origin - HTTP | MDN

The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given origin.

developer.mozilla.org

 이 외에 토큰 작업을 위한 쿠키 컨트롤이나 리다이렉트에 대한 방법은 아래 공식문서를 참고하기 바란다.

 

Routing: Route Handlers | Next.js

Using App Router Features available in /app

nextjs.org

 

반응형

'next.js' 카테고리의 다른 글

next Error handling  (0) 2023.07.27
next loading UI  (0) 2023.07.27
next로 ISR 구현하기  (0) 2023.07.26
next 동작원리 읽기  (0) 2023.07.26
page 라우팅? app 라우팅? 뭐가 좋은데?  (0) 2023.07.25
Comments