React프로젝트에 아래목록 작업이 모두 완료되었다면 이번엔 로컬DB mysql과 연결을 해보겠습니다. 

 

Mysql이 설치되어있지 않다면 Mysql사이트(링크)에서 다운받아주세요.
이후 설명과정은 DB 사용자정보와 샘플용 테이블데이터가 모두 준비되었다는 가정하에 진행합니다.

 

 

 

프로젝트폴더에 Mysql관련 패키지 설치하기

npm install mysql
yarn add mysql

 

 

 

server폴더에 DB정보파일 생성

프로젝트폴더의 server디렉토리안에 'config'폴더를 생성한 뒤 'db.js'파일을 생성합니다.

 

 

그리고나서 아래 코드를 입력합니다.

이 정보들은 server.js에서 db에 연결요청시 사용됩니다.

var mysql = require('mysql');
const db = mysql.createPool({
    host : 'localhost',
    user : 'react_test',
    password : '1111',
    database : 'react_test'
});

module.exports = db;

 

 

server.js에서 db정보 요청

파일 상단에 DB커넥션 객체를 추가해주고 '/api/products'로 데이터요청 발생시 쿼리를 날려

DB로부터 가져온 정보를 products라는 이름으로 보내줍니다. (DB data는 배열형태로 가져옴)

const express = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
const db = require('./config/db');

app.get('/api/products', (req, res) => {
    db.query("SELECT * FROM mall_test", (err, data) => {
        if(!err) res.send({ products : data });
        else res.send(err);
    })
})

app.listen(PORT, () => {
    console.log(`Server On : http://localhost:${PORT}/`);
})

 

 

 

브라우저 콘솔에서 출력된 db데이터 확인

app.js를 조금 수정했습니다. db정보가 레코드마다 배열의 원소로 저장되어 보내지므로 this.state.hello를 빈배열로 초기화합니다. 그리고 받은 데이터는 개발모드 콘솔로 확인해봅니다.

 

import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hello : [],
    }
  }

  componentDidMount() {
    this._getHello();
  }

  _getHello = async() => {
    const res = await axios.get('/hello');
    this.setState({ hello : res.data.hello })
    console.log(this.state.hello);
  }

  render() {
    return(
      <>
        <h3>get DB data(브라우저 개발모드 콘솔확인)</h3>
      </>
    )
  }
}

export default App;

 

server.js를 재실행하여 mysql에 저장된 데이터가 잘 출력되는지 확인합니다.

+ Recent posts