Nextjs은 백엔드까지 동시에 제공하는 full stack framework입니다. Route Handlers를 사용하면 별도의 백엔드를 구축하지 않고 Nextjs API 서버까지 구축할 수 있습니다. 자세한 내용은 Route Handlers를 참고해주세요.
여기서는 Json-server를 이용해서 간단하게 백엔드를 구축하고, 뒤에서 백엔드를 사용하는 방법을 알려드립니다.
절차
1. json-server 실행
1 | npx json-server --port 9999 -- watch db.json |
2. db.json 파일 수정
1 2 3 4 5 6 7 8 9 10 11 12 13 | { "topics" : [ { "id" : 1, "title" : "html" , "body" : "html is .." }, { "id" : 2, "title" : "css" , "body" : "css is .." }] } |
3. http:localhost:9999/topics로 접속
4. 개발자 도구 Network 창에서 ESC키를 눌러서 콘솔창 열기
5. 글목록 읽기
1 2 3 | const result = await resp.json(); console.log(result); |
6. 글추가
1 2 3 4 5 6 7 8 9 | method: "POST" , body: JSON.stringify({ title: "js" , body: "js is ..." }), headers: { "content-type" : "application/json" , }, }); const result = await resp.json(); console.log(result); |
7. 글 읽기
1 2 3 | const result = await resp.json(); console.log(result); |
8. 글 수정
1 2 3 4 5 6 7 8 | method: 'PATCH' , body: JSON.stringify({title: 'css3' , body: 'css3 is ...' }), headers: { 'content-type' : 'application/json' }}) const result = await resp.json(); console.log(result); |
9. 글 삭제
1 2 3 4 5 | method: 'DELETE' , }) const result = await resp.json(); console.log(result); |