본문 바로가기

Node.js

Express 웹서버 구축하고 CRUD 게시판 구현 하기


Express.js 프레임워크를 사용해 백엔드 웹 서버를 구축하고, 간단한 게시판 프로그램(CRUD)을 구현하는 방법을 설명하겠습니다. CRUD는 Create(생성), Read(읽기), Update(수정), Delete(삭제) 기능을 포함합니다. 이 게시판은 게시글을 추가하고, 목록을 읽으며, 수정하고, 삭제하는 기능을 갖추게 됩니다.

데이터베이스는 mongoDB를 사용합니다.


1. 프로젝트 초기 설정

먼저, 프로젝트를 초기화하고 필요한 패키지를 설치합니다.

 

mkdir board-app
cd board-app
npm init -y
npm install express ejs body-parser mongoose

npm init -y은 package.json을  설정을 기본으로 한다는 것입니다.

 


2. 폴더 구조

다음과 같은 폴더 구조를 사용하겠습니다

 

board-app/
├── app.js
├── models/
│   └── Post.js
├── views/
│   ├── index.ejs
│   ├── edit.ejs
│   └── new.ejs
└── public/
    └── style.css

 

 


3. 게시글 모델(Post) 생성

models/Post.js 파일을 만들어 게시글 스키마를 정의합니다.

// models/Post.js
const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Post', postSchema);

 

 


 

4. app.js 파일 설정

Express 서버를 설정하고 라우팅을 구성합니다.

// app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Post = require('./models/Post');

const app = express();

// MongoDB 연결
mongoose.connect('mongodb://localhost:27017/board', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB 연결 성공'))
  .catch((err) => console.log(err));

// 미들웨어 설정
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.use(express.static('public'));

// 홈 - 게시글 목록 보기
app.get('/', async (req, res) => {
  const posts = await Post.find();
  res.render('index', { posts });
});

// 게시글 작성 폼
app.get('/new', (req, res) => {
  res.render('new');
});

// 게시글 생성
app.post('/posts', async (req, res) => {
  const { title, content } = req.body;
  const post = new Post({ title, content });
  await post.save();
  res.redirect('/');
});

// 게시글 수정 폼
app.get('/posts/:id/edit', async (req, res) => {
  const post = await Post.findById(req.params.id);
  res.render('edit', { post });
});

// 게시글 수정
app.post('/posts/:id', async (req, res) => {
  const { title, content } = req.body;
  await Post.findByIdAndUpdate(req.params.id, { title, content });
  res.redirect('/');
});

// 게시글 삭제
app.post('/posts/:id/delete', async (req, res) => {
  await Post.findByIdAndDelete(req.params.id);
  res.redirect('/');
});

// 서버 실행
app.listen(3000, () => {
  console.log('서버가 실행 중입니다. http://localhost:3000');
});

 

 


5. EJS 뷰 파일 작성

뷰 파일을 작성하여 사용자 인터페이스를 만듭니다.

views/index.ejs (게시글 목록)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>게시판</title>
  <link rel="stylesheet" href="/style.css">
</head>
<body>
  <h1>게시판</h1>
  <a href="/new">새 게시글 작성</a>
  <ul>
    <% posts.forEach(post => { %>
      <li>
        <h2><%= post.title %></h2>
        <p><%= post.content %></p>
        <a href="/posts/<%= post._id %>/edit">수정</a>
        <form action="/posts/<%= post._id %>/delete" method="post" style="display:inline;">
          <button type="submit">삭제</button>
        </form>
      </li>
    <% }) %>
  </ul>
</body>
</html>

 

 

views/new.ejs (게시글 작성 폼)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>새 게시글 작성</title>
</head>
<body>
  <h1>새 게시글 작성</h1>
  <form action="/posts" method="post">
    <label>제목: <input type="text" name="title" required></label><br>
    <label>내용: <textarea name="content" required></textarea></label><br>
    <button type="submit">작성</button>
  </form>
</body>
</html>

 

views/edit.ejs (게시글 수정 폼)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>게시글 수정</title>
</head>
<body>
  <h1>게시글 수정</h1>
  <form action="/posts/<%= post._id %>" method="post">
    <label>제목: <input type="text" name="title" value="<%= post.title %>" required></label><br>
    <label>내용: <textarea name="content" required><%= post.content %></textarea></label><br>
    <button type="submit">수정</button>
  </form>
</body>
</html>

 

 


6. CSS 파일 작성

public/style.css 파일에 간단한 스타일을 추가합니다.

body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
  padding: 20px;
}

h1 {
  color: #333;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 5px;
}

a {
  color: blue;
  text-decoration: none;
}

button {
  background-color: red;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 3px;
  cursor: pointer;
}

button:hover {
  background-color: darkred;
}

서버 실행

모든 파일을 설정한 후 서버를 실행합니다.

명령어 $ node app.js

 

브라우저에서 http://localhost:3000으로 접속하면 게시판이 보입니다. 게시글을 추가하고 수정하거나 삭제할 수 있습니다.

'Node.js' 카테고리의 다른 글

Express 서버 연동(기본)  (0) 2024.10.12