Mi Lugarcito

React & Node.js - 고객(Customer) DB 테이블 구축 및 Express와 연동하기 [React와 Node.js를 활용한 고객 관리 시스템 개발 강의] 본문

React & Next.js

React & Node.js - 고객(Customer) DB 테이블 구축 및 Express와 연동하기 [React와 Node.js를 활용한 고객 관리 시스템 개발 강의]

selene park 2021. 3. 12. 15:11

 

 

 

CUSTOMER 테이블 먼저 생성하기

USE management;

CREATE TABLE CUSTOMER(
	id INT PRIMARY KEY AUTO_INCREMENT,
    image VARCHAR(1024),
    name VARCHAR(64),
    birthday VARCHAR(64),
    gender VARCHAR(64),
    job VARCHAR(64)

)DEFAULT CHARACTER SET UTF8 COLLATE utf8_general_ci;


insert into CUSTOMER values(1,'https://placeimg.com/64/64/1', '홍길동','112233','남자','학생1');
insert into CUSTOMER values(2,'https://placeimg.com/64/64/2', '홍길자','112233','남자','학생2');
insert into CUSTOMER values(3,'https://placeimg.com/64/64/3', '홍길순','112233','남자','학생3');

select * from CUSTOMER;

 

server 쪽에 잇는 gitignore 에 아래 코드 추가하기 (aws rds 비밀번호 유출되지 않도록 하기 위해서)

# database
/database.json

 

 

server 파일에 database.json 만들어서 아래 코드 작성하기

 

//db 접속을 위한 정보 입력하기
{
    "host" : "management-tutorial.ct8ynnxtsbtv.ap-northeast-2.rds.amazonaws.com",
    "user" : "user",
    "password": "12345678",
    "port" : "3306",
    "database" : "management"
}

 

 

그리고 gitignore 에서 이미 database.json 처리를 했기때문에 여기서 회색으로 보여지게 된다. 

 

mysql 라이브러리 설치하기

npm install --save mysql

 

server.js

//디비 환경설정 정보 읽어오기
const fs = require('fs');

const express =require('express');
const bodyParser = require('body-parser');
const app =express();
const port = process.env.port || 5000;

app.use(bodyParser.json());//기본적으로 REST API 에서는 데이터 주고받을때 json 데이터 형식으로 주고받음
app.use(bodyParser.urlencoded({extended:true}));



 
//디비연동 코드
const data = fs.readFileSync('./database.json');
const conf = JSON.parse(data);
const mysql = require('mysql');
const connection = mysql.createConnection({
  host : conf.host,
  user : conf.user,
  password : conf.password,
  port : conf.port,
  database : conf.database
});
connection.connect();



app.get('/api/customers', (req,res) => {
    //디비 접근하기
    connection.query(
      //쿼리 날리기
      "select * from CUSTOMER",
      (err, rows, fields)=>{
        res.send(rows);
      }
       
    );
});


app.listen(port, ()=> console.log(`listening on port ${port}`));

 

 

App.js

import logo from './logo.svg';
import './App.css';
import { Component } from 'react';
import Customer from './components/Customer';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableHead from '@material-ui/core/TableHead';
import TableBody from '@material-ui/core/TableBody';
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
//프로그래스바 라이브러리 추가하기
import CircularProgress from  '@material-ui/core/CircularProgress';


//cs적용하기
import {ThemeProvider, withStyles} from '@material-ui/core/styles';

const styles=theme=>({
  root:{
    width:"100%",
    //marginTop:ThemeProvider.spacing.unit*3,
    overflowX:"auto"
  },
  table:{//이후 가로스크롤바가 생김
    minWidth:1080
  },
  //프로그래스바
  progress: {
    margin:theme.spacing(2)
  }
});




/*
리액트의 component life cycle을 가지고 있다. 
1) constructor() 
2) componentWillMount()
3) render()
4) componentDidMount()
// props or state => 변경되는 경우에는 shouldComponentUpdate()함수가 사용되어서 실질적으로 다시 render 함수 불러와서 뷰 갱신한다. 
*/




//고객정보를 서버에 접속해서 가져올 수 있도록 해야한다. (데이터가 변경될 수 있음)
//props는 변경될 수 없는 데이터를 명시할때 사용 & state 는 변경될 수 있는 데이터를 명시할 때 사용한다. 
class App extends Component{

  state={
    customers : "",
    //프로그래스바
    completed : 0 //퍼센트를 알려주는것
  }

  //실제 api 서버에 접근하도록 하기 (componentDidMount : 데이터 받아오는 작업)
  componentDidMount(){
    //프로그래스 바
    this.timer=setInterval(this.progress, 20); //0.02초마다 한번씩 프로그래스 함수 실행되도록 설정 
    //컴포넌트 준비 완료
    this.callApi()
      .then(res => this.setState({customers:res}))
      .catch(err => console.log(err));
  }

  //api 불러오기 (비동기적 수행)
  //const : 변수
  callApi = async() =>{
    const response = await fetch('/api/customers');//로컬호스트 접근
    const body = await response.json();
    return body;
  }
  


  //프로그래스 애니매이션 효과
  progress =() => {
    const {completed} =this.state;
    this.setState({completed:completed >=100 ? 0 : completed +1});
  }



  render(){
    const {classes} =this.props;
    return(
        <Paper className={classes.root}> 
            <Table className={classes.table}> 
              <TableHead>
                <TableRow>
                  <TableCell>번호</TableCell>
                  <TableCell>이미지</TableCell>
                  <TableCell>이름</TableCell>
                  <TableCell>생년월일</TableCell>
                  <TableCell>성별</TableCell>
                  <TableCell>직업</TableCell>
                </TableRow>
              </TableHead>

              <TableBody>
                  {this.state.customers ? this.state.customers.map(c=>{ 
                    return (<Customer key={c.id} id={c.id} image={c.image} name={c.name} birthday={c.birthday} gender={c.gender} job={c.job} />); 
                  }) : 
                  <TableRow>
                    <TableCell colSpan="6" align="center">
                      <CircularProgress className={classes.progress} variant="determinate" value={this.state.completed}/>
                    </TableCell>
                  </TableRow>
                  }
              </TableBody>
            </Table>
        </Paper>

    );
  }
}

export default withStyles(styles)(App);

 

yarn dev로 서버 재실행해주면 아래와 같이 잘 실행된다!!!!