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

17. 연락처 추가

by 갱생angel 2024. 3. 15.

views - <add.ejs> : 연락처 추가 페이지

action : 어떤 경로로 요청할 것인지 지정

<%- 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/add" method="POST" id="add-user"> <!--/contact/add로 POST 요청-->
    <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" />
        </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" />
        </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" />
        </div>
      </div>
      <button type="submit">저장하기</button>
    </div>
  </form>
</main>
<%- include('./include/_footer') %>

 

controllers - <contactController.js> : 입력한 name, email, phone을 POST 요청해서 추가

.redirect() : 요청 경로를 강제로 바꿈

(...)

//GET view add contact form, /contact/add : add.ejs 파일을 렌더링해서 보여주기
const addContactForm = (req, res) => {
  res.render("add");
};

//Post contact, /contact/add : 입력한 name, email, phone을 추가
const createContect = asynchHandler(async (req, res) => {
  const { name, email, phone } = req.body;
  if (!name || !email || !phone) {
    res.status(400).send("No Input Value");
  }
  const contact = await Contact.create({ name, email, phone });
  res.status(201).redirect("/contact"); //성공 시 /contact로 이동
});

(...)

module.exports = {
  getAllContact,
  createContect,
  getContact,
  updateContact,
  deleteContact,
  addContactForm, //addContactForm 외부로 내보냄
};

 

routes - <contactRoutes.js> : /add 경로 추가

const express = require("express");
const router = express.Router();
const {
  getAllContact,
  createContect,
  getContact,
  updateContact,
  deleteContact,
  addContactForm, //addContactForm 임포트
} = require("../controllers/contactController");

router.route("/").get(getAllContact);
router.route("/add").get(addContactForm).post(createContect); // /contact/add로 GET, POST 지정
router.route("/:id").get(getContact).put(updateContact).delete(deleteContact);

module.exports = router;

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

19. 회원가입, bcrypt  (0) 2024.03.19
18. 연락처 추가, 삭제  (0) 2024.03.16
16. include, 연락처 표시  (0) 2024.03.14
15. EJS  (0) 2024.03.13
14. CRUD  (0) 2024.03.12