입력값을 몽고DB에 저장 후 표시
-add.js 페이지 추가
-백엔드-
controllers - <cantactController-2.js>
(...)
//Post all contact, /contact/add
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로 이동
});
(...)
routes - <contactRoutes-2.js> : /add 경로 추가
const express = require("express");
const router = express.Router();
const {
getAllContact,
createContect,
getContact,
updateContact,
deleteContact,
} = require("../controllers/contactController-2");
router.route("/").get(getAllContact);
router.route("/add").post(createContect); // /add 경로 추가, POST 지정
router.route("/:id").get(getContact).put(updateContact).delete(deleteContact);
module.exports = router;
-프론트엔드-
react-router-dom : 리액트를 위한 라우팅 라이브러리
>> npm install react-router-dom
index.js
App.js
component
-header.js
page
-main.js
-add.ejs
css
-style.css
<App.js> : 라우팅 설정
※BrowserRouter : 웹브라우저에서 react-router를 사용하여 라우팅을 할 수 있도록 해주는 컴포넌트
※Routes : <Route>를 childern으로 가지는 컴포넌트
※Route : path(경로), element(렌더 링할 페이지)를 props으로 갖는 컴포넌트
import React from "react";
import Main from "./page/main";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Add from "./page/add";
function App() {
return (
<div>
<BrowserRouter>
<Routes>
<Route index element={<Main />} />
<Route path="/add" element={<Add />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
page - <main.js>
※useNavigate : 각 페이지의 경로를 이동하는 훅
import React, { useEffect, useState } from "react";
import axios from "axios";
import "../css/style.css";
import Header from "../component/header";
import { useNavigate } from "react-router-dom";
function Main() {
const [lists, setLists] = useState([]);
const navigate = useNavigate();
const goToAdd = () => { navigate("/add") }; //연락처 추가 페이지로 이동하는 함수
useEffect(() => {
axios
.get("http://localhost:8080/contact")
.then((res) => setLists(res.data));
});
return (
<div>
<Header />
<div className="site-main">
<div className="button-box">
<button onClick={goToAdd}>+ 연락처 추가</button>
</div>
<table className="table">
<thead>
<tr>
<th>이름</th>
<th>이메일</th>
<th>전화번호</th>
<th> </th>
</tr>
</thead>
<tbody>
{lists.map((list, index) => {
return (
<tr key={index}>
<td>{list.name}</td>
<td>{list.email}</td>
<td>{list.phone}</td>
<td>
<button>수정</button>
<button>삭제</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}
export default Main;
page - <add.js>
※axios.post() : POST 요청
import React, { useState } from "react";
import Header from "../component/header";
import { useNavigate } from "react-router-dom";
import axios from "axios";
function Add() {
const [name, setName] = useState(""); //사용자 이름
const [email, setEmail] = useState(""); //사용자 이메일
const [phone, setPhone] = useState(""); //사용자 연락처
const changeName = (e) => { setName(e.target.value) };
const changeEmail = (e) => { setEmail(e.target.value) };
const changePhone = (e) => { setPhone(e.target.value) };
const addForm = (e) => { //연락처 추가 함수
e.preventDefault();
const userData = { name: name, email: email, phone: phone };
if (name === "" || email === "" || phone === "") { //입력을 하지 않음
alert("입력해주세요.");
} else { //입력 했을 시
axios
.post("http://localhost:8080/contact/add", userData) //POST 요청
.then((res) => goToMain());
}
};
const navigate = useNavigate();
const goToMain = () => { navigate("/") }; //메인 페이지로 이동하는 함수
return (
<div>
<Header />
<div className="site-main">
<div className="button-box">
<button onClick={goToMain}>연락처 목록</button>
</div>
<h2>연락처 추가</h2>
<p>연락처 정보를 추가합니다</p>
<form onSubmit={addForm}>
<div className="user-info">
<div>
<label>이름</label>
<input type="text" value={name || ""} onChange={changeName} />
</div>
<div>
<label>메일 주소</label>
<input type="text" value={email || ""} onChange={changeEmail} />
</div>
<div>
<label>전화번호</label>
<input type="text" value={phone || ""} onChange={changePhone} />
</div>
<button type="submit">저장하기</button>
</div>
</form>
</div>
</div>
);
}
export default Add;
'Do it Node.js > React BackEnd' 카테고리의 다른 글
6. 로그인 페이지 (0) | 2024.03.20 |
---|---|
5. 회원가입 페이지 (0) | 2024.03.19 |
4. 연락처 수정 페이지, 삭제 (0) | 2024.03.17 |
2. 연락처 목록 페이지, Axios (0) | 2024.03.14 |
1. 백엔드 연결 (0) | 2024.03.14 |