본문 바로가기
Do it Node.js/EJS BackEnd

18. 연락처 추가, 삭제

by 갱생angel 2024. 3. 16.

method-override : form의 POST 요청을 덮어 씌워서 PUT, DELETE 요청을 할 수 있게 해주는 미들웨어

  -form은 기본적으로 GET, POST 요청 밖에 할 수 없음

>> npm install method-override

 

<app.js> : method-override 등록

const express = require("express");
const dbConnect = require("./config/dbConnect");
const methodOverride = require("method-override"); //method-override 가져옴

const app = express();

app.set("view engine", "ejs");
app.set("views", "./views");

dbConnect();

app.get("/", (req, res) => {
  res.status(200).send("Hello Node");
});

app.use(express.static("./public"));
app.use(methodOverride("_method"));  //method-override를 등록
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/contact", require("./routes/contactRoutes"));

app.listen(3000, () => {
  console.log("3000 포트에서 서버 실행 중");
});

 

controllers - <contactController.js>

findByIdAndUpdate() : 도큐먼트 검색과 수정을 한꺼번에 해주는 함수

findByIdAndDelete() : 도큐먼트 검색과 삭제을 한꺼번에 해주는 함수

(...)

//Get get contact, /contact/:id
const getContact = asynchHandler(async (req, res) => {
  const contact = await Contact.findById(req.params.id);
  res.status(200).render("update", { contact: contact }); //update.js를 렌더링
});

//Put update contact, /contact/:id
const updateContact = asynchHandler(async (req, res) => {
  const { name, email, phone } = req.body;
  const contact = await Contact.findByIdAndUpdate(
    req.params.id, //id 값을 수정
    { name, email, phone }, //name, email, phone 값을 수정
    { new: true } //수정한 도큐먼트를 반환
  );
  res.status(200).redirect("/contact"); //수정 후 /contact로 이동
});

//Delete delete contact, /contact/:id
const deleteContact = asynchHandler(async (req, res) => {
  await Contact.findByIdAndDelete(req.params.id);
  res.status(200).redirect("/contact"); //수정 후 /contact로 이동
});

(...)

 

views - <index.ejs>

<%- include('./include/_header') %>
<main id="site-main">
  <div class="button-box">
    <a href="/contact/add" class="btn btn-light"
      ><i class="fa-solid fa-user-plus"></i>연락처 추가</a
    >
  </div>
  <table class="table">
    <thead>
      <tr>
        <th>이름</th>
        <th>메일 주소</th>
        <th>전화번호</th>
        <th>&nbsp;</th>
      </tr>
    </thead>
    <tbody>
      <% contact.forEach(contacts => { %>
      <tr>
        <td><%= contacts.name %></td>
        <td><%= contacts.email %></td>
        <td><%= contacts.phone %></td>
        <td>
          <a href="/contact/<%= contacts._id %>" class="btn update" title="수정">
          <!--지정한 id 도큐먼트 수정 페이지로 이동-->
            <i class="fas fa-pencil-alt"></i>
          </a>
          <form action="/contact/<%= contacts._id %>?_method=DELETE" 
          	method="POST" 
          	style="display: inline"
          > <!--지정한 id 도큐먼트 삭제-->
            <input type="submit" class="btn delete" title="삭제" value="X" />
          </form>
        </td>
      </tr>
      <% }); %>
    </tbody>
  </table>
</main>
<%- include('./include/_footer') %>

 

views - <update.ejs> : 수정 페이지

<%- include('./include/_header') %>
<main id="site-main">
  <div class="button-box">
    <a href="/contact" class="btn btn-light"
      ><i class="fa-solid fa-list"></i>연락처 목록</a
    >
  </div>
  <h2>연락처 수정</h2>
  <p>연락처 정보를 수정합니다.</p>
  <form action="/contact/<%= contact._id %>?_method=PUT" method="POST" id="add-user"> 
  <!-- 수정 -->
    <div class="user-info">
      <div class="col-12">
        <label for="name" class="col-form-label">이름(Full Name)</label>
        <div>
          <input type="text" class="form-control" name="name" id="name" value="<%= contact.name %>" />
          <!--수정 전 이름 값을 나타냄-->
        </div>
      </div>
      <div class="col-12">
        <label for="email" class="col-form-label">메일 주소(E-mail)</label>
        <div>
          <input type="text" class="form-control" name="email" id="email" value="<%= contact.email %>" />
          <!--수정 전 이메일 값을 나타냄-->
        </div>
      </div>
      <div class="col-12">
        <label for="phone" class="col-form-label">전화번호(Mobile)</label>
        <div>
          <input type="text" class="form-control" name="phone" id="phone" value="<%= contact.phone %>" />
          <!--수정 전 전화번호 값을 나타냄-->
        </div>
      </div>
      <button type="submit">수정하기</button>
    </div>
  </form>
</main>
<%- include('./include/_footer') %>

'Do it Node.js > EJS BackEnd' 카테고리의 다른 글

20. 로그인, 토큰  (0) 2024.03.19
19. 회원가입, bcrypt  (0) 2024.03.19
17. 연락처 추가  (0) 2024.03.15
16. include, 연락처 표시  (0) 2024.03.14
15. EJS  (0) 2024.03.13