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

2. 연락처 목록 페이지, Axios

by 갱생angel 2024. 3. 14.

몽고DB에 저장된 데이터를 가져와 표시

  -header.js, main.js 페이지 추가

 

-백엔드-

 

controllers - <cantactController-2.js>

(...)

//Get all contact, /contact
const getAllContact = asynchHandler(async (req, res) => {
  const contact = await Contact.find();
  res.status(200).send(contact); //모든 자료가 담긴 contact 변수를 전송
});

(...)

-프론트엔드-

 

Axios : 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리

>> npm install axios

 

index.js

App.js

component

  -header.js

page

  -main.js

css

  -style.css

 

component - <header.js> : 사이트 헤더

import React from "react";
import "../css/style.css";

function Header() {
  return (
    <div>
      <header className="border-shadow">
        <div className="container">
          <nav>
            <p>My Contact</p>
          </nav>
        </div>
      </header>
    </div>
  );
}

export default Header;

 

page - <main.js> : 연락처 페이지

&nbsp; : 공백을 나타내는 유니코드

axios.get() : GET하는 함수

import React, { useEffect, useState } from "react";
import axios from "axios";
import "../css/style.css";
import Header from "../component/header";

function Main() {
  const [lists, setLists] = useState([]);

  useEffect(() => { //axios.get() 함수를 써서 데이터 가져오기
    axios
      .get("http://localhost:8080/contact")
      .then((res) => setLists(res.data));
  });

  return (
    <div>
      <Header />
      <div className="site-main">
        <div className="button-box">
          <button>+ 연락처 추가</button>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>이름</th>
              <th>이메일</th>
              <th>전화번호</th>
              <th>&nbsp;</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;

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

6. 로그인 페이지  (0) 2024.03.20
5. 회원가입 페이지  (0) 2024.03.19
4. 연락처 수정 페이지, 삭제  (0) 2024.03.17
3. 연락처 추가 페이지, react-router-dom  (0) 2024.03.15
1. 백엔드 연결  (0) 2024.03.14