본문 바로가기
C++ 200제/코딩 IT 정보

Node.js express 연동: Mysql 접속 및 데이터 표시

by vicddory 2020. 5. 1.

Node.js Express <-> Mysql 연동Node.js Express <-> Mysql 연동


Node.js 프레임워크 express를 사용하여 Mysql에 접속하기 위한 샘플 코드입니다.


목차

1. 환경

2. Express 환경 구축

3. Mysql 모듈 사용법


환경

  • OS CentOS Linux release 8.0.1905 (Core)
  • node V10.16.3
  • npm 6.9.0
  • express 4.17.1

Express 환경 구축

아래의 순서로서 구축합니다.


npm init -y
npm i -D express
npm install -D express-generator


mysql 모듈을 설치합니다


npm install --save mysql


Node.js Express <-> Mysql 연결용 DB 및 table을 만들어 둡니다.


## user 로그인
mysql -u user -p
테스트용 DB 작성
mysql> create database testdb;
테스트용 테이블 작성
mysql> use testdb;
mysql> create table title (id int, title varchar(10));
데이터 작성
mysql> insert into title values (1,'test1');
mysql> insert into title values (2,'test2');
.
.
mysql> insert into title values (5,'test5');


Mysql 모듈 사용법

mysql 모듈을 이용하여 위에서 만든 table에 연결(접속)합니다.

프로젝트 아래에 app.js 생성하고 아래처럼 편집합니다.


const express = require('express')
const ejs = require('ejs')
const mysql = require('mysql')
const app = express()
 
app.set('ejs'ejs.renderFile)
 
const con = mysql.createConnection({
    host'localhost',
    user'user',
    password'비밀번호 설정',
    database'testdb'
  });
 
app.get('/', (reqres=> {
 
    con.query('select * from title'function (errresultsfields) {
        if (errthrow err
        res.render('index.ejs', { contentresults })
    });
 
})
 
app.listen(3000, () => {
    console.log('server start')
})


다음 views 폴더를 프로젝트 아래에 만들고, index.ejs 파일을 아래 코드처럼 편집합니다.

Node.js Express <-> Mysql 연동 결과를 보여줄 html 화면입니다.


<!DOCTYPE html>
<html>
 
<head>
    <link rel="stylesheet"
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
 integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
 crossorigin="anonymous">
</head>
 
<body>
    <div class="container" style="margin-top:50px;">
        <table class="table">
            <thead class="thead-dark">
                <tr>
                    <th scope="col">id</th>
                    <th scope="col">title</th>                    
                </tr>
            </thead>
            <tbody>
            <% for(let i in content) { %>
            <tr>
                <% let obj = content[i]; %>
                <th>
                    <%= obj.id %>
                </th>
                <th>
                    <%= obj.title %>
                </th>
            </tr>
            <% } %>
            </tbody>
        </table>
    </div>
</body>
</html>


실행합니다.


node app.js


브라우저에서 http://private IP:3000 접속하면 title 테이블의 데이터가 표시됩니다.



댓글