728x90

따라하면서

순서, 필요한 내용 적기 

<이 순간, 최고의 강의_별점 백개 드립니다_>

https://www.youtube.com/watch?v=re3OIOr9dJI 

 

client -react 프론트

server -express, 백단

 

client/ npx create-react-app .

(.은 현재 위치를 의미함)

server/ npm init 

해서 package.json 생성하고

필요한 

mysql express 

설치

 

client/

Login.js

import { useState } from "react";
import "./login.css";

function Login() {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);
  const [country, setCountry] = useState("");
  const [position, setPosition] = useState("");
  const [wage, setWage] = useState(0);

  const onChangefun = (event) => {
    setName(event.target.value);
    console.log(event.target.value);
  };
  return (
    <div className="login">
      <div className="information">
        <label>Name : </label>
        <input type="text" onChange={onChangefun}></input>
        <label>Age : </label>
        <input
          type="number"
          onChange={(event) => {
            setAge(event.target.value);
          }}
        ></input>
        <label>Country : </label>
        <input
          type="text"
          onChange={(event) => {
            setCountry(event.target.value);
          }}
        ></input>
        <label>Position : </label>
        <input
          type="text"
          onChange={(event) => {
            setPosition(event.target.value);
          }}
        ></input>
        <label>Wage: </label>
        <input
          type="number"
          onChange={(event) => {
            setWage(event.target.value);
          }}
        ></input>
        <button>직원 등록</button>
      </div>
    </div>
  );
}

export default Login;

 

server/

index.js

const express = require("express");
const app = express();

app.listen(3001, () => {
  console.log("your server is running on 3001~! yeah");
});

 

이제 mysql 설정해줄거임

 

mysql 워크벤치에서 

스키마 생성

테이블 생성

server/

디비저장 코드 입력

 

const express = require("express");
const app = express();
const mysql = require("mysql");

const db = mysql.createConnection({
  user: "root",
  host: "localhost",
  password: "비밀번호",
  database: "crudtest",
});

app.post("/create", (req, res) => {
  const name = req.body.frontname;
  const age = req.body.frontage;
  const country = req.body.frontcountry;
  const position = req.body.frontposition;
  const wage = req.body.frontwage;

  db.query(
    "INSERT INTO employees (name, age, country, position, wage) VALUES (?,?,?,?,?)",
    [name, age, country, position, wage],
    //콜백함수
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        res.send("values Inserted");
      }
    }
  );
});

app.listen(3001, () => {
  console.log("your server is running on 3001~! yeah");
});

client/

import { useState } from "react";
import "./login.css";
import Axios from "axios";

function Login() {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);
  const [country, setCountry] = useState("");
  const [position, setPosition] = useState("");
  const [wage, setWage] = useState(0);

  const addEmployee = () => {
    Axios.post("http://localhost:3001/create", {
      frontname: name,
      frontage: age,
      frontcountry: country,
      frontposition: position,
      frontwage: wage,
    }).then(() => {
      console.log("success");
    });
  };

  const onChangefun = (event) => {
    setName(event.target.value);
    console.log(event.target.value);
  };
  return (
    <div className="login">
      <div className="information">
        <label>Name : </label>
        <input type="text" onChange={onChangefun}></input>
        <label>Age : </label>
        <input
          type="number"
          onChange={(event) => {
            setAge(event.target.value);
          }}
        ></input>
        <label>Country : </label>
        <input
          type="text"
          onChange={(event) => {
            setCountry(event.target.value);
          }}
        ></input>
        <label>Position : </label>
        <input
          type="text"
          onChange={(event) => {
            setPosition(event.target.value);
          }}
        ></input>
        <label>Wage: </label>
        <input
          type="number"
          onChange={(event) => {
            setWage(event.target.value);
          }}
        ></input>
        <button onClick={addEmployee}>직원 등록</button>
      </div>
    </div>
  );
}

export default Login;

프런트에서 백 전달할때 

우리는 api허용해주기 위해서 cors 라이브러리 사용할거임

npm i cors

 

server/ index.js 파일에

const cors = require("cors");
app.use(cors());

추가

 

 

 

 

근데 여전히 막상보면 백으로 못넘어옴

이렇게 req.body 콘솔 찍어보면 

undefined 뜸 

 

json 미들웨어를 제공안해서였음

프런트에서 보낼때 

 

 

index.js/

app.use(express.json());

이거 추가

 

유튜브영상에서는 이거 추가하면 db넣기 성공했는데 난 안됨. ㅎ

 

 db에 안들어가고 

에러 뜸

Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

 

 

이거 mysql에 외부접근안돼서 그런거라고 함  

그래서 이걸로 해결가능하다고 함( 비번 사용해서 db계정사용하게끔 하는 설정인듯!)

 

+해결방법중에 mysql2쓰는 것도 있음 이번에는 안해봄 

 ALTER user '[유저]'@'localhost' IDENTIFIED WITH mysql_native_password by '[비번]';

 바꿔주기 위해서 mysql로 ㄱㄱ

mysql에 바로 use mysql하면 접속이 안됨

mysql -u root -p도 당연히 안됨

 

 

'use'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는
배치 파일이 아닙니다

워크벤치 경로로 들어가서 해야함~~~

C:\Program Files\MySQL\MySQL Server 8.0\bin

 

 

cd C:\Program Files\MySQL\MySQL Server 8.0\bin

mysql -u root -p

 

이제 mysql켜짐

 

mysql>

 

 

계정 뭐있는지 확인 먼저 함

 

SELECT user,authentication_string,plugin,host FROM mysql.user;

 

내가 쓸 root계정 있는거 확인함

 

 

 

 

 ALTER user '[유저]'@'localhost' IDENTIFIED WITH mysql_native_password by '[비번]';

 

flush privileges;

 

 

 

index.js 

서버 끄고 다시 실행

node index.js

로 실행

 

 

직원등록 눌러서 보내보면 

 

잘 들어왔다~!~!~!~!~!

 

 

 

이제 우리가 할거는

백-> 프런트로 

정보 가져오는걸 할거임

우리는 필요할 때 정보를 봐야하니까 

 

 

client/

//초기에는 빈배열이니까 []로 넣어줌 
 const [employeesList, setEmployeesList] = useState([]);
 //가져올 함수// 백가져온 응답반은걸 콘솔로 보여주겠음 response가져온거의 data로
   const getEmployee = () => {
    Axios.get("http://localhost:3001/employees").then((response) => {
      setEmployeesList(response.data);
    });
  };
  
  
 //버튼
   <div className="showDB">
      //버튼눌렀을 때 가져올 함수 실행
        <button className="showDB-button" onClick={getEmployee}>
          show employees
        </button>
      </div>

 

server/

app.get("/employees", (req, res) => {
//db에서 employess테이블 다 가져와
  db.query("SELECT * FROM employees", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

버튼 누르면

이건 response임 

object 객체로 가져옴

(status 200 -> 작동한거임)

이안에 우리가 원하는 정보가 잘 담겨져있음

 

 

이제 백에서 가져온 것들을 화면에 띄워줄거임

맵함수 사용해서

배열에서 하나씩 꺼내오기 

 

        <div>
          {employeesList.map((val, index) => {
            return (
              <div className="employee">
                <h3>{val.name}</h3>
                <h3>{val.age}</h3>
                <h3>{val.country}</h3>
                <h3>{val.position}</h3>
                <h3>{val.wage}</h3>
              </div>
            );
          })}
        </div>

성공~~~

 

 

근데 다른 방법도 있대 

post에 넣고 바로 화면에 띄우게 하는법

 

const addEmployee = () => {
    console.log(name, "dfdfd");
    Axios.post("http://localhost:3001/create", {
      frontname: name,
      frontage: age,
      frontcountry: country,
      frontposition: position,
      frontwage: wage,
    }).then(
      //   () => {
      //   console.log("success");
      // }
      () => {
        //기존 배열에 방금 입력한 걸 추가하고 그걸 setEmployessList함수에 넣음! 배경은 뜨는데 값이 안띄워지네..흠
        //암튼 여러 방법이 있다고 함 있다가 해보자
        setEmployeesList([
          ...employeesList,
          {
            frontname: name,
            frontage: age,
            frontcountry: country,
            frontposition: position,
            frontwage: wage,
          },
        ]);
      }
    );
  };

나는 왜인지 빈값만 뜸

 

db에는 잘들어갔는데...

왜 안뜨는 것인가...

이부분은 다른 날에 해보겟음

 

 

이제 

삭제 하고 수정하고 다음에 해봐야지

db에서 가져온 목록 선택해서 나열하게 하고

이런 것도 해보고 싶네 

 

아 그리고 지금은 새로고침하면 db에서 블러온 애들이 화면에서 사라지거든

그것도 막아야겠다.

728x90

+ Recent posts