[Next.js] api

찐새·2022년 5월 19일
1

next.js

목록 보기
7/41
post-thumbnail

api

api 생성

pages내에 api 디렉토리를 만든 후 api로 사용할 파일 생성.

import { NextApiRequest, NextApiResponse } from "next";

export default async function api(
  req: NextApiRequest,
  res: NextApiResponse
) {
	res.status(200/401/...);
}

api 통신

fetch("api/url", {
  method: 'POST', // GET, POST, PUT, DELETE 등
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{
  	'Content-Type': 'application/json'
  }
})

headers를 명시하지 않으면 api 응답에서 원하는 데이터를 받지 못할 수 있음.

// headers (x)
export default async function api(
  req: NextApiRequest,
  res: NextApiResponse
) {
    console.log(req.body); // {"email":"adads@email.com"}
  	console.log(req.body.email); // undefined
}

//headers (o)
export default async function api(
  req: NextApiRequest,
  res: NextApiResponse
) {
    console.log(req.body); // { email: 'adads@email.com' }
  	console.log(req.body.email); // adads@email.com
}

주의사항

next.js에서 api를 작성할 때는 함수 자체를 export default해야 한다.
무슨 말인지 이해 못하고 적어뒀다. 고차함수(Higher Order Function(HOF)) 개념이란다. 나중에 이해하거든 다시 정리할 것.

http method 주요 상태코드

  • 200: 요청 성공
  • 400: 클라이언트에서 Request할 때 발생한 문제
  • 403: 클라이언트의 접근 권한 없을 때 발생한 문제. 401과 달리 서버가 클라이언트 정체를 알고 있음.
  • 405: 허용되지 않은 메서드 사용.
  • 500: 서버에서 발생한 문제

추가 상태코드 참고 MDN http 상태코드


참고
노마드 코더 - 캐럿마켓 클론코딩
MDN fetch

profile
프론트엔드 개발자가 되고 싶다

0개의 댓글