본문 바로가기

프론트엔드 공부/react

json-server-api 활용한 restful (get,post,put,delete,patch)/login구현 crud

1.기존 프론트 폴더 이외에 server-api폴더(db대용)를 생성하고

vsc에서 새로운 터미널을 열어준후 npm init으로 nodemodules및 package.json생성

(새로운 터미널열어주는이유: db 로컬 같이 열어주기 위해서)

2.db.json파일을 생성하고 내용물 넣어줌

3.axios, json-server npm으로 설치 후

터미널창을 각각 열어 서버와 db 생성

서버생성"node server.js"

db생성 "npx json-server ./db.json --port 8000"(json-server 8000을 생성하고 db.json파일을 읽음) 

//db.json

{
  "users": [
    {
      "id": "1",
      "firstName": "bon",
      "lastName": "aoe",
      "email": "bohb@gmail.com",
      "age": 30,
      "companyId": "1"
    },
    {
      "id": "2",
      "firstName": "fon",
      "lastName": "foe",
      "email": "fohb@gmail.com",
      "age": 14,
      "companyId": "2"
    	},
    ],
        "companines": [
      {
        "id": "1",
        "name": "Apple",
        "description": "dddddddddd"
      },
      {
        "id": "2",
        "name": "Samsung",
        "description": "dddddddddd"
      },
      {
        "id": "3",
        "name": "Apple2",
        "description": "dddddddddd"
      }
    ]
      }

 

 

//server.js
const jsonServer = require("json-server");
const server = jsonServer.create();
const path = require("path");
const router = jsonServer.router(path.join(__dirname, "db.json"));
const middlewares = jsonServer.defaults();

// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares);

// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser);

server.use(router);

let port = 80;
server.listen(port, () => {
  console.log(`JSON Server is running, port(${port})`);
});

4.form 태그로 데이터 submit 원하는 페이지에서 axios활용하여 get,put,patch,delete 실행

//api는 db로컬주소 빼두려고 만든건데 사용 안함
import api from "../../../api/contact";
import axios from "axios";
import React, { useEffect, useState } from "react";

export default function App() {
  const [login, setLogin] = useState([]);
  const [inputs, setInputs] = useState({
    name: "",
    id: "",
  });

  //api
  useEffect(() => {
    createUsers();
    // deleteUsers();
  }, []);

  /*get users*/
  const getUsers = () => {
    return axios.get("http://localhost:3006/users").then((res) => {
      setLogin(res.data);
      console.log(res.data);
    });
  };
  /*create users*/
  const createUsers = () => {
    return axios.post("http://localhost:3006/users", {
      name: inputs.name,
      id: inputs.id,
    });
  };
  /*일부업데이트*/
  const updateUsers = () => {
    return axios.patch("http://localhost:3006/users/2", {
      firstName: "수정된이름",
    });
  };
  /*id 새로 생성 업데이트*/
  const newupdateUsers = () => {
    return axios.put("http://localhost:3006/users/2", {
      reset: "this is reset",
    });
  };
  /*users delete*/
  const deleteUsers = () => {
    return axios.delete(`http://localhost:3006/users/1`);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const id = e.target.id.value;
    const name = e.target.name.value;
    const lastname = e.target.lastname.value;
    console.log(`name ${name}, lastname ${lastname},id ${id}`);
  };
  const handleOnChange = (e) => {
    setInputs({
      ...inputs,
      [e.target.name]: e.target.value,
    });
    console.log(inputs.id);
  };
  return (
    <>
      <form
        onSubmit={handleSubmit}
        onChange={handleOnChange}
        className="ml-4 flex flex-col w-2/12"
      >
        <label>id</label>
        <input className="border" type="text" name="id" />
        <label>firstname</label>
        <input className="border" type="text" name="name" />

        <label>lastname</label>
        <input className="border" type="text" name="lastname" />
        <label>email</label>
        <input className="border" type="text" name="email" />
        <label>age</label>
        <input className="border" type="text" name="age" />
        <button className="bg-red-100 p-3 mt-4" onClick={createUsers}>
          Submit
        </button>
        <button className="bg-blue-200 p-3 mt-4" onClick={deleteUsers}>
          Delete
        </button>
        <button className="bg-green-300 p-3 mt-4" onClick={updateUsers}>
          수정
        </button>
        <button className="bg-red-500 p-3 mt-4" onClick={newupdateUsers}>
          전체수정
        </button>
      </form>
    </>
  );
}

5.로그인 구현

원리는 위와 같음(모달창만 구현)

import axios from "axios";
import React, { useState, useContext, useRef, useEffect } from "react";
import { useHistory } from "react-router";
import common from "../datas/common";//가상 로컬포트주소 넣어둠
import { MainContext } from "../datas/Store";//contextapi

const Example = (props) => {
  const history = useHistory();
  const [modal, setModal] = useState(true);
  const { onLoggedUser } = useContext(MainContext);
  const [login, setLogin] = useState({
    userId: "",
    pass: "",
  });

  const refId = useRef();
  const refPass = useRef();

  /*loginmodal*/
  const showModal = () => {
    setModal(!modal);
  };
  /*handleonChange*/
  const handleOnChange = (e) => {
    setLogin({
      ...login,
      [e.target.name]: e.target.value,
    });
  };
  /*searchusers*/
  const searchUsers = () => {
    axios.get(common.POSTGRE_URL + "patient").then((res) => {
      const allData = res.data;
      const correct = allData.find(
        (correctUser) =>
          correctUser.userId === login.userId && correctUser.pass === login.pass
      );
      if (correct === undefined || correct == null || correct === "") {
        alert("잘못입력하셨습니다.");
        refId.current.value = "";
        refPass.current.value = "";
      } else {
        alert(`${correct.name}님 반갑습니다`);
      }
    });
    // console.log(common.POSTGRE_URL);
    // console.log("search", searchUserId, searchPass);
  };

  /*login한 회원 넘기기*/
  const verifiedUser = () => {
    searchUsers();
    axios.post(common.SERVER_URL + "mobilelogin", login).then((res) => {
      // console.log(res.data);
      onLoggedUser(login);
      history.push("/intro");
    });
  };

  return (
    <>
      <section id="main" className="w-full h-full">
        <div className="main_title flex items-center flex-col pt-36">
          <span className="main_top text-xl bg-gray-100 w-full text-center block">
            lorem
          </span>
          <span className="main_top text-xl bg-gray-100 w-full text-center block">
            lorem
          </span>
          <h1 className="text-2xl font-bold text-gray-800 pt-10 pb-2">
            lorem
          </h1>
          <span
            className="main_eng text-xs font-bold"
            style={{ letterSpacing: 5 }}
          >
            RESXIUM<strong style={{ color: "rgb(238, 211, 61)" }}>lorem</strong>
          </span>
          <span className="main_eng text-xs font-bold">lorem</span>
        </div>
        <div
          className="kakao_login w-full absolute bottom-4 flex flex-col items-center cursor-pointer"
          onClick={showModal}
        >
          <span className="kakao_login_img w-10/12 h-14 mb-6 pointer">
            <img
              src="https://m.apostrophes.kr/web/img/kakao_1sec_login.png"
              alt="kakao"
            />
          </span>
          <p className="align-center text-s pt-8">
            로그인에 문제가 있을 시 아래의 메일로 문의해주세요.
          </p>
          <p>(문의: help@heringsglobal.com)</p>
        </div>
        {modal === false ? (
          <div className="loginmodal bg-white w-full h-full absolute top-0 flex flex-col justify-center items-center">
            <div
              className="bg-gray-300 text-xl p-2 text-white w-2/4 mb-10"
              style={{ textAlign: "center" }}
            >
              로그인 모달입니다.
            </div>
            <form className="flex flex-col" onChange={handleOnChange}>
              <span>ID</span>
              <input
                ref={refId}
                className="bg-gray-100"
                type="text"
                name="userId"
              />
              <span>PASSWORD</span>
              <input
                ref={refPass}
                className="bg-gray-100"
                type="text"
                name="pass"
              />
            </form>
            <button
              className="border p-2 mt-6 hover:bg-gray-300 hover:text-white"
              style={{ transition: "all ease 0.3s" }}
              onClick={verifiedUser}
            >
              로그인
            </button>
            <button
              className="bg-gray-300 p-1 text-xl text-white absolute bottom-20"
              onClick={showModal}
            >
              닫기
            </button>
          </div>
        ) : null}
      </section>
    </>
  );
};

export default Example;