본문 바로가기

React

React - Mysql 연동하기, 연결(데이터 저장)

반응형

1. 준비

  • mysql

mysql workbench를 사용할 것이다.

2. database 만들기 및 express에 연결하기

 

database와 table을 만들어주자. 

나는 tistory라는 database와 test라는 table을 만들거다.

CREATE DATABASE tistory;

 

CREATE TABLE `tistory`.`test` (
  `test_key` INT NOT NULL AUTO_INCREMENT,
  `test_body` VARCHAR(45) NULL,
  PRIMARY KEY (`test_key`));

key는 AI(Auto Increment)이다.

 

이제 express에 mysql에 연결해보자

먼저 mysql모듈을 설치해주자

npm install mysql

이전 코드

2020/10/15 - [React] - React와 Express연동하기 2

에서 mysql을 연결하는 코드를 추가해준다

server.js

const express = require("express"); 
const app = express();
const port = 3001; // react의 기본값은 3000이니까 3000이 아닌 아무 수
const cors = require("cors");
const bodyParser = require("body-parser");
const mysql = require("mysql"); // mysql 모듈 사용

var connection = mysql.createConnection({
    host : "localhost",
    user : "root", //mysql의 id
    password : "root", //mysql의 password
    database : "tistory", //사용할 데이터베이스
});

connection.connect();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());

app.get('/', (req, res) =>{
    res.send('혁이는 코딩 중!')
})

app.post("/idplz", (req,res)=>{
    const test = req.body.test;
    // console.log(req.body);
    connection.query("INSERT INTO test (test_body) values (?)",[test],
    function(err,rows,fields){
        if(err){
            console.log("실패");
            // console.log(err);
        }else{
            console.log("성공");
            // console.log(rows);
        };
    });

    
});

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

뜻대로 잘 되지 않아서 console.log를 조금 사용하였다 ! 하나씩 차근차근 로그를 확인해가며

코딩하는 것이 정말 중요한것 같다. 아는 것도 틀릴 때가 있다.

3. 코드수정

App.js

import React, { Component } from 'react'
import './App.css';
export default class App extends Component {
  state = {
    testbody : "",
  }

  handleChange =(e)=>{
    this.setState({
      [e.target.name] : e.target.value,
    });
  }

  submitId = ()=>{
    const post ={
      test : this.state.testbody,
    };
   
    fetch("http://localhost:3001/idplz", {
      method : "post", // 통신방법
      headers : {
        "content-type" : "application/json",
      },
      body : JSON.stringify(post),
    })
    .then((res)=>res.json())
    .then((json)=>{
      this.setState({
        testbody : json.text,
      });
    });
  };

  render() {
    return (
      <div>
        <input onChange={this.handleChange} name ="testbody"/>
        <button onClick = {this.submitId}>Submit</button>
        <h1>{this.state.testbody}</h1>
      </div>
    )
  }
}

 코드가 이해가 안된다면 이전 포스팅들을 찾아보길 추천드립니당

 

4. 결과

 

db까지 잘들어갔는지 확인할수 있다.

 

오늘은 저장하는 것을 해보았으니 다음에는 불러오는 것을 해보자.

반응형