[React, express] React 랑 express.js 연결하기. useRef() 사용

Suji Kang·2023년 9월 21일
0

🐾 React 랑 연결하기 express.js로

먼저, react폴더안에
npm install express --save
express를 설치해줘야함 설치하면 package.json
"express": "^4.18.2" 확인가능

nodemon도 설치해줘 껏다켯다 귀찮으니깐
npm install nodemon 설치하기 ❗️
근데, 나는 저번에 global로 전역으로 설치해줘서 설치 안해줘도됨
설치하면 package.json"nodemon": "^3.0.1" 확인가능


🐾 지금까지 서버를 킬때 React와 express를 따로따로 실행시켰지❓

express 와 react를 동시에 실행가능❓

🔎 Concurrently 라는 라이브러리를 활용하면 한번에 실행시킬수가 있어 ❗️
📝 package.json start 명령어를 둘다 실행할수있도록 설정하여 npm start 를 하면 동시에 서버클라이언트가 켜지게 설정

먼저 라이브러리를 설치해, concurrently 라이브러리도 설치해줘.

npm i concurrently --save

설치하면 package.json"concurrently": "^8.2.1" 확인가능


📝 react 폴더server 폴더 만들고
app.js파일을 만든다

const express = require('express');

const app = express();
const port = 3002;

app.listen(port, () => {
    console.log(`listening at http://localhost:${port}`);
});

server 폴더로 가서 실행

cd server
nodemon app 실행

이제 또 react 폴더가서 가서 실행

 cd react
 npm start 실행

이거를 따로따로 하나씩 실행하지않고 어떻게하면 동시에 실행이 가능할까 ❓

package.json 에서 명령어 수정이 필요 ❗️
npm start 하면

export PORT=3001 && react-scripts start

👉👉 react만 실행하고싶을때🌟

👉👉 server만 실행 시키고 싶을때🌟

 "server": "cd server && nodemon app",


🔎npm run server하면❓, cd server 해서 server 폴더 로 가고, nodemon app을 실행시켜줘❗️ 라는뜻.

🔎 npm run client를 실행하면 ❓3001포트에 리액트앱을 실행시켜줘❗️

🔎 해석하자면 ❓
npm start 실행하면 ❓
👉👉 둘중에 하나라도 켜져있으면 kill(다꺼줘) 그리고 서버와 클라이언트를 둘다 실행해줘.

"concurrently --kill-others-on-fail \"npm run server\" \"npm run client\""

이렇게 쓰면 너무 기니까, start 에 넣어주고 npm start 만 실행❗️
👇
그러면이제, 동시에 localhost 3001,3002 실행 성공❗️


react 폴더안에 src 폴더 안에
expressTest.js 를 만들자❗️

import axios from "axios";

    const onExpressClick = () => {
        axios.get('/api')
            .then((res) => {
                console.log('success res', res);
            }).catch((err) => {
                console.log('fail err', err);
            });
    }
    //axios get 요청 해줘 어디에? /api에

    return (
        <>
            <h1>express test page</h1>
            <button onClick={onExpressClick}>
                button
            </button>
        </>
    );
}

export default ExpressTestPage;

app.js

app.get('/api', (req, res) => {
  res.send('Hello World!');
});
// "/api" 주소로 get 요청(req)이 오면 data 에 'Hello World!'응답(res) send 한다.

🐾 CORS 정책 (Cross-Origin Resource Sharing)

📝 CORS란 ❓

CORS(교차 출처 리소스 공유)는 웹사이트가 다른 웹사이트에서 데이터를 가져오거나 요청할 때, 브라우저에서 그 요청을 허용하거나 차단하는 보안 규칙. 이것을 통해 웹사이트가 안전하게 데이터를 공유하고 브라우저가 악의적인 요청을 방지할 수 있다.

같은 컴퓨터 안에서 서로 다른 프로그램이 다른 포트에서 동작하는 프로그램에 접근을 하려면 CORS 정책을 수정해야한다.

🔎 2가지 방법이 있다. 선택은 알아서 😇

📝1. 클라이언트 쪽에서 설정

🔎 http-proxy-middleware 라이브러리 설치
설치하면, package.json"http-proxy-middleware": "^2.0.6" 확인가능

npm i http-proxy-middleware

setupProxy.js 파일 만들고, 주소 끝에 '/api' 로 끝나면, 서버 포트쪽으로 보내게 설정을 만들어준다
👇
localhost:3001/apiget 요청해줘 하면 ❗️
실직적으로는 ......🤨
localhost:3002/apiget 요청이 가버린다.

👉👉 react에서는 주소 끝을 api로 끝나는 주소는 사용할 수 없다

setupProxy.js는 자동으로 실행되는것.

setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(
        createProxyMiddleware(
            '/api',
          //'/api'로 가면, 
            {
                target: 'http://localhost:3002',
              //localhost3002로 경로를 가줘라
                changeOrigin: true,
            })
    );
}

expressTest.js

import axios from "axios";

    const onExpressClick = () => {
        axios.get('/api')
            .then((res) => {
                console.log('success res', res);
            }).catch((err) => {
                console.log('fail err', err);
            });
    }
    //axios get 요청 해줘 어디에? /api에

📝 2.서버쪽에서 설정(express 파일에서 설정하는 방법)

CORS 라이브러리를 설치한다

npm install cors
	const cors = require('cors');

	const app = express();
	const port = 3002;

    app.use(cors({origin: 'http://localhost:3001'}));
    //해당 코드 한줄 추가
    // (3001번포트 허용하겠다는 의미)

	//리액트에서는 요청할 때
    //localhost:3002 get요청 직접적으로 해도 상관없음

MYSQL연결하기

'/api'로 가면 포트넘버 3002로 간다.

MYSQL Workbench를 열고, table query 먼저 만든다❗️

create table employees(
   id int auto_increment primary key,
    emp_name varchar(20) not null, 
    salary int 
);

insert into employees ( emp_name, salary)
values 
('홍길동', 1000),
('김철수', 2000),
('박영희', 500),
('김사과', 10000),
('임꺽정', 700),
('오렌지', 600);

select * from employees;

mysql 설치

npm i mysql2

server 폴더에 app.js

 // 모든사원 조회
app.get('/api/employees', (req, res) => {
    // mysql 에서 employees 테이블의 모든 데이터(행,컬럼)를 조회.
    pool.query('SELECT * FROM employees', (err, rows, fields) => {
        // console.log('rows', rows); 우리가필요한 데이터
        // console.log('fields', fields); 거의 쓸일없음
        res.json(rows);//응답할래, json형태로  rows(데이터를)넣어서
    });
});

// 사원 한명 추가
app.post('/api/employees', (req, res) => {

});

const mysql = require('mysql2');

//mysql설정
const pool = mysql.createPool({
    host: 'localhost',
    user: 'board23user',
    database: 'board23',
    password: '1234',
    port: 3306 
});
//.env파일에 **mysql 설정**을 올려줘야함 그래야 git에 안올라감 (이건연습용 이니까 일단은 괜찮음)

expressTest.js

import axios from "axios";

  const getEmployees = () => {
        axios.get('/api/employees') //localhost 3001으로 get요청을 하고있는거야~
            .then((res) => { //then. 성공이 끝나면 이 함수 실행시켜줘.
                console.log('success res', res.data);
                setEmployees(res.data);
            }).catch((err) => {
                console.log('fail err', err);
            });
    }
   
 return (
        <>  
            <h1>express test page</h1>
            <button onClick={getEmployees}>mysql 데이터를 가져와 보겠습니다.</button>
            <button onClick={fetchEmployees}>fetchEmployees</button>
        </>
    );
}

axios로 받아오면,

 express                      react axios
   res.json('강수지')  	-->    res.data에 '강수지'이 들어있음
   res.json(10)         -->    res.data에 10이 들어있음
   res.json([1,2,3])    -->    res.data에 [1,2,3]이 들어있음

fetch 로 받아오면,

 express                      react fetch
   res.json('강수지')  	-->    res.json() data에'강수지'이 들어있음
   res.json(10)         -->    res.json() data에 10이 들어있음
   res.json([1,2,3])    -->    res.json() data에 [1,2,3]이 들어있음

expressTest.js

 const fetchEmployees = () => {
        fetch('/api/employees')
            .then((res) => {
                return res.json();
            }).then((data) => {
                console.log('data', data);
            }).catch((err) => {
                console.log('err', err);
            });
    }
 
 return (
        <>
            <h1>express test page</h1>
            <button onClick={fetchEmployees}>fetchEmployees</button>
        </>
    );
}

📌 가지고온 data, map으로 보여주기 ❗️

expressTest.js

import { useState } from "react";

const ExpressTestPage = () => {
    const [employees, setEmployees] = useState([]);
  
    const getEmployees = () => {
        axios.get('/api/employees') //localhost 3001으로 get요청을 하고있는거야~
            .then((res) => { //then. 성공이 끝나면 이 함수 실행시켜줘.
                console.log('success res', res.data);
                setEmployees(res.data);//data를 넣어준다
            }).catch((err) => {
                console.log('fail err', err);
            });
    }
  
   return (
        <>
 <h1>입력!</h1>
      <label>
        사원이름
        <input ref={empNameRef} id="emp_name"/>
      </label>
      <label>
        사원 봉급
        <input id="salary"/>
      </label>
      <button onClick={addEmp}>추가하기!</button>

  <h1>사원목록!</h1>
            {employees.map((e) =>
                <div key={e.id}>
                    <div>사원이름:
                        {e.emp_name}
                    </div>
                    <div>
                        salary: {e.salary}
                    </div>
                </div>
            )}
      {/* <div>사원이름 : 홍길동, 사원번호 : 1, 봉급 : 1000</div>
      <div>사원이름 : 홍길동, 사원번호 : 1, 봉급 : 1000</div>
      <div>사원이름 : 홍길동, 사원번호 : 1, 봉급 : 1000</div>
      <div>사원이름 : 홍길동, 사원번호 : 1, 봉급 : 1000</div> */}
  </>
    );
}

사원추가하기❗️

useRef()

null값이 들어가면,

useRef(null);//useRef결과는 객체이다. key값은 current
👇
{
 current : null
}

suji라는 값이 들어가면,

useRef('suji');
👇
{
 current : suji
}
import { useRef } from "react";

const empNameRef = useRef(null);//useRef결과는 객체이다
    // document.querySelector('#emp_name')
    // document.querySelector를 통해 태그를 가져오는것이 아닌
    // Ref 객체를 통해 태그를 가져온다 
    console.log(empNameRef.current.value);

return (
    <>
      <h1>입력!</h1>
      <label>
        사원이름
        <input ref={empNameRef} id="emp_name" />
        //ref에 empNameRef 함수를 넣어준다
      </label>
      <label>
        사원 봉급
        <input id="salary" />
      </label>
      <button onClick={addEmp}>추가하기!</button>
     </>
  );
}

input에 ref속성을 넣어줘!

<input ref={empNameRef} id="emp_name" />
  //ref에 empNameRef 함수를 넣어준다

current방에 input태그를 넣어줘!

그러면console에 출력하면❓
input에 입력하는 값이 empNameRef안에있는 current방에 value번쨰방 = 사용자가 입력한 값이 나온다.

console.log(empNameRef.current.value);

useRef 가

document.querySelector('#emp_name')

를 대체함

profile
나를위한 노트필기 📒🔎📝

0개의 댓글