[Next.js] Backend
Nextjs은 백엔드까지 동시에 제공하는 full stack framework입니다. Route Handlers를 사용하면 별도의 백엔드를 구축하지 않고 Nextjs API 서버까지 구축할 수 있습니다.백엔드를 구축하여 내용을 갖고와 동적으로 내용을 표시해봅시다.
- #next.js
이 시리즈의 다른 글 Next.js · 8/16
- 1 [Next.js] Next.js란 무엇인가?
- 2 [Next.js] 심플 앱 세탁
- 3 [Next.js] 빌드와 배포
- 4 [Next.js] 뼈대 만들기 -Layout& Page
- 5 [Next.js] Routing
- 6 [Next.js] Single Page Application
- 7 [Next.js] 정적인 자원 사용하기 - public
- 8 [Next.js] Backend
- 9 [Next.js] 글 목록 가져오기
- 10 [Next.js] 읽기 기능 구현
- 11 [Next.js] 생성 기능 구현 - Client Component
- 12 [Next.js] Cache
- 13 [Next.js] 필요할 때 Update, Delete 기능 보이기
- 14 [Next.js] 글 수정
- 15 [Next.js] 글 삭제
- 16 [Next.js] 환경 변수
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);
이 글은 원래 Velog에 2024-07-08에 올린 글입니다. 원문: [Next.js] Backend
마지막 수정: