Nextjs은 백엔드까지 동시에 제공하는 full stack framework입니다. Route Handlers를 사용하면 별도의 백엔드를 구축하지 않고 Nextjs API 서버까지 구축할 수 있습니다.
백엔드를 구축하여 내용을 갖고와 동적으로 내용을 표시해봅시다.
여기서는 Json-server를 이용해서 간단하게 백엔드를 구축하고, 뒤에서 백엔드를 사용하는 방법을 알아볼 생각입니다.
터미널에서 명령어를 작성하였습니다.
npx json-server@0.17.4 --port 9999 --watch db.json
밑은 실행 하였을 때의 db.json파일입니다.
//db.json
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}
//터미널
Resources
http://localhost:9999/posts
http://localhost:9999/comments
http://localhost:9999/profile
Home
http://localhost:9999
Resources라는 부분에 주소가 나옵니다. posts에 접근하고 싶다면 위의 주소로 접근하면 됩니다.
하지만 저는 topics라는 주소로 들어가면 topic들이 출력되도록 만들고 싶기에 db.json을 수정할 것 입니다.
//db.json
"topics": [
{"id":1, "title":"html", "body": "html is ..."},
{"id":2, "title":"css", "body":"css is ..."}
],
이렇게 코드를 추가하였고 파일에 있는 내용을 json형태로 응답하는 것을 볼 수 있었습니다. 이 데이터를 자바스크립트로 갖고오는 작업을 한번 해볼 것 입니다.
웹페이지에서 개발자 도구를 열어 콘솔로 들어간 후 , fetch명령어를 사용해 볼 것입니다.
//글 읽기
const resp = await fetch('http://localhost:9999/topics/')
const result = await resp.json();
console.log(result);
/*
실행 결과
(2) [{…}, {…}]
0
:
{id: 1, title: 'html', body: 'html is ...'}
1
:
{id: 2, title: 'css', body: 'css is ...'}
length
:
2
[[Prototype]]
:
Array(0)
*/
//글 수정
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);
/*
결과
{id: 2, title: 'css3', body: 'css3 is ...'}
body
:
"css3 is ..."
id
:
2
title
:
"css3"
[[Prototype]]
:
Object
*/
//글 삭제
const resp = await fetch('http://localhost:9999/topics/2', {
method:'DELETE',
})
const result = await resp.json();
console.log(result);