[Node.js 개발자 되기] 1. REST 이해하기
REST 1. REST란? REST란 자원의 이름을 구분하여 자원의 상태를 주고받는 과정을 말합니다. 쉽게 풀어서 말하자면 Client와 서버가 손쉽게 대화(요청, 응답)하는 과정이라 생각하면 됩니다. 2. 자원의
pventi.tistory.com
이 전글에서 REST를 통해 Client와 Server가 대화하는 방법에 대해 알아봤습니다.
그렇다면 REST를 이용하여 다음 내용을 이해하기 위해 기본적인 게시글을 만들어보겠습니다.
게시글을 만들기 전
프로그래밍하기 전 게시글에 필요한 기능들을 생각해 보겠습니다.
1) 게시글 생성 (Create)
3) 게시글 화면 보여주기 (Read)
2) 게시글 수정 (Update)
3) 게시글 수정 (Delete)
이 세 가지 작업을 CRUD 작업이라 합니다.
준비물
게시글을 생성하고 수정, 삭제하려면 서버에서 게시글을 불러올 수 있어야겠죠?
그러기 위해서 필요한 것이 데이터베이스입니다. 게시글뿐만 아니라 회원정보, 기타 정보 등 서버에 저장되는 대부분의 정보들은 데이터베이스에 저장된다고 생각하시면 됩니다.
클라이언트에서 REST를 통해 서버로 요청을 하면 서버는 필요한 정보들을 데이터베이스에서 가져와 클라이언트에게 보내줍니다.
저희는 mongoDB라는 데이터베이스를 사용할 겁니다.
두 번째로는 정적인 웹페이지를 동적으로 작동시키기 위해 뷰엔진에서 ejs를 사용할 겁니다.
세 번째로는 jquery입니다. 클라이언트에서 게시글을 요청하기 위해 ajax를 사용할 텐데 jquery를 이용하여 손쉽게 ajax를 요청하기 위해 필요합니다.
몽고디비는 몽고디비 사이트에 가입해 주신 다음 무료버전으로 클러스터 생성해 주세요.
MongoDB: The Developer Data Platform
Get your ideas to market faster with a developer data platform built on the leading modern database. MongoDB makes working with data easy.
www.mongodb.com
추가로 설치할 npm은 아래와 같습니다.
npm i ejs dotenv mongoose
ejs : 뷰엔진
dotenv : 환경설정 파일 (외부로 공개되서는 안 되는 중요한 정보를 기입합니다)
mongoose : 몽고디비와 연결하기 위한 npm
코드 수정
3.1 기존 html파일 확장자를 ejs로 변경해 주면서 header.ejs, footer.ejs 두 부분을 때어서 분리해 줍니다.
3.1.1 header.ejs
헤더 부분에 보면 jquery cdn 추가하는 부분이 있습니다. (따로 코드블록 걸어두겠습니다.)
<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script>
3.1.2 footer.ejs
3.1.3 index.ejs
index.ejs 에 상단부 하단부에 잘라낸 header와 footer를 include 해줍니다.
<%-include('header.ejs')%>
<%-include('footer.ejs')%>
이 처럼 해주는 이유는 매번 새로운 페이지가 필요할 때마다 새로운 html에 똑같은 코드(불필요한)를 작성하는 경우가 빈번하게 발생합니다. 위처럼 만 들 경 우 중복되는 코드를 최소한 할 수 있고 관리 차원면에서도 용이합니다.
3.1.4 index, header, footer 파일을 views라는 폴더로 옮겨줍니다.
3.3 node.js 에서 view engine(ejs)를 사용하기 위해 아래 코드를 index.js에 작성해 줍니다.
const ejs = require('ejs')
app.set('view engine', 'ejs')
view engine을 등록해 주면 이전에 html 불러오는 코드를 변경해주셔야 합니다.
// 변경전
app.use("/", (req, res, next) => {
res.status(200).sendFile(__dirname + "/public/index.html")
})
// 변경후
app.use("/", (req, res, next) => {
res.status(200).render("index")
})
기본적으로 render는 views 폴더에서 매핑해서 불러오기 때문에 반드시 views 폴더 안에 index.ejs 파일이 있어야 합니다.
현재는 node.js이기에 html과 ejs 관련코드는 생략하겠습니다.
3.4 mongoose
3.4.1. env 파일에 작성해 둔 URI를 불러와 mongoose로 연결해 줍니다.
파일경로 : index.js
3.4.2 포스트 모델을 만들어줍니다.
파일경로 : models/post.model.js
const mongoose = require('mongoose')
// id 값 자동 증가를 위한 npm
const autoIncrement = require('mognoose-auto-increment')
const connecton = mongoose.createConnection(procee.env.MONGO_URI)
autoIncrement.initialize(connection)
// 스키마 선언
const postSchema = new mongoose.Schema({
subject : {
type : String,
required : true,
},
author : {
type : String,
required : true
},
content : {
type : String,
required : true
},
},{
timestamps : true
})
postSchema.plugin(autoIncrement.plugin, { model : 'Post', fiedl : 'postId' })
module.exports = mongoose.Model("Post", postSchema)
3.4.3 CRUD 기능 사용자 메서드로 지정
// Create
postSchema.statics.create = function(payload) {
const post = new this(payload);
return post.save();
}
// Read
postSchema.statics.findAll = function() {
return this.find({})
}
postSchema.statics.findByPostId = function(postId) {
return this.findOne({ postId })
}
// Update
postSchema.statics.updateByPostId = function(postId, payload) {
return this.findOneAndUpdate({ postId }, payload, { new : true })
}
// Delete
postSchema.statics.deleteByPostId = function(postId) {
return this.remove({ postId })
}
위 사진은 post.model.js의 전체 내용입니다.
3.4.4 Rest 요청을 받을 부분 생성
파일경로 : index.js
const Post = require('/models/post.model.js')
// create
app.post("/api/post/create", (req, res, next) => {
Post.create(req.body)
.then(post => res.status(200).render('index'))
.catch(e => res.status(500).send(e))
})
// Read All
app.get("/api/post/list", (req, res, next) => {
Post.find()
.then(posts => res.status(200).json(posts))
.catch(e => res.status(500).send(e))
})
// Read One
app.get("/api/post/:postId", (req, res, next) => {
Post.findOneByPostId(req.params.postId)
.then(post => res.status(200).render('post', { post })
.catch(e => res.status(500).send(e))
})
// update
app.post("/api/post/update", (req, res, next) => {
const { postId } = req.body;
Post.updateByPostId(postId, req.body)
.then(post => res.status(200).redirect(`/api/post/${postId}`))
.catch(e => res.status(500).send(e)
})
// delete
app.delete("/api/post/:postId", (req, res, next) => {
Post.deleteByPostId(req.params.postId)
.then(() => res.status(200).render('index'))
.catch(e => res.status(500).send(e))
})
결과
기능 개발을 집중적으로 하다 보니 디자인 처리는 추후에 할 예정입니다.
GitHub - dotredbee/rest-basic: rest-basic server 1
rest-basic server 1. Contribute to dotredbee/rest-basic development by creating an account on GitHub.
github.com
'Backend > Node.js' 카테고리의 다른 글
[Node.js 개발자 되기] 6. 로그인 구현 (0) | 2023.02.23 |
---|---|
[Node.js 개발자 되기] 5. HTTP프로토콜 특징 그리고 세션과 쿠키 (0) | 2023.02.23 |
[Node.js 개발자 되기] 4. BootStrap 적용 (0) | 2023.02.22 |
[Node.js 개발자 되기] 3. 코드 정리하기 (0) | 2023.02.22 |
[Node.js 개발자 되기] 1. REST 이해하기 (0) | 2023.02.21 |