[DB] node.js 서버와 mysql 연동
2021. 7. 28. 15:25ㆍ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 : 'host',
user : 'user',
password : 'password',
port:port,
database : 'database'
});
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 || 3001;
const db = require('./config/db');
app.get('/api/products', (req, res) => {
db.query("SELECT * FROM users", (err, data) => {
if(!err) res.send({ products : data });
else res.send(err);
})
})
//DB INSERT
let sql = "INSERT INTO users (name,email,password,roles) VALUES(?,?,?,?)";
let params = ['test', 'test@hanmail.net', 'dh111111', 'user'];
db.query(sql, params, function(err, rows,fields){
if(err){
console.log(err);
}
else{
console.log(rows.insertId);
}
})
app.listen(PORT, () => {
console.log(`Server On : http://localhost:${PORT}/`);
})
브라우저 콘솔에서 출력된 db데이터 확인
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에 저장된 데이터가 잘 출력되는지 확인합니다.