생활코딩

Coding Everybody

코스 전체목록

닫기

backend

Nextjs은 백엔드까지 동시에 제공하는 full stack framework입니다. Route Handlers를 사용하면 별도의 백엔드를 구축하지 않고 Nextjs API 서버까지 구축할 수 있습니다. 자세한 내용은 Route Handlers를 참고해주세요. 

여기서는 Json-server를 이용해서 간단하게 백엔드를 구축하고, 뒤에서 백엔드를 사용하는 방법을 알려드립니다. 

절차

1. json-server 실행

npx json-server --port 9999 --watch db.json

 

2. db.json 파일 수정

{
  "topics": [
    {
      "id": 1,
      "title": "html",
      "body": "html is .."
    },
    {
      "id": 2,
      "title": "css",
      "body": "css is .."
    }]
}

 

3. http:localhost:9999/topics로 접속

 

4. 개발자 도구 Network 창에서 ESC키를 눌러서 콘솔창 열기

 

5. 글목록 읽기 

const resp = await fetch('http://localhost:9999/topics/')
const result = await resp.json();
console.log(result);

 

6. 글추가 

const resp = await fetch("http://localhost:9999/topics", {
  method: "POST",
  body: JSON.stringify({ title: "js", body: "js is ..." }),
  headers: {
    "content-type": "application/json",
  },
});
const result = await resp.json();
console.log(result);

 

7. 글 읽기

const resp = await fetch('http://localhost:9999/topics/1')
const result = await resp.json();
console.log(result);

 

8. 글 수정

const resp = await fetch('http://localhost:9999/topics/2', {
  method:'PATCH', 
  body: JSON.stringify({title:'css3', body:'css3 is ...'}),
  headers: {
    'content-type': 'application/json'
  }})
const result = await resp.json();
console.log(result);

 

9. 글 삭제

const resp = await fetch('http://localhost:9999/topics/2', {
    method:'DELETE', 
})
const result = await resp.json();
console.log(result);

댓글

댓글 본문
  1. 딸기공방
    230912
  2. 어흥
    230813
버전 관리
egoing
현재 버전
선택 버전
graphittie 자세히 보기