nodejs express mysql db 연결하기

단밤v 2023. 1. 3. 01:27
728x90
반응형

안녕하세요. 터미네입니다.

 

이번 포스팅은 nodejs express에

db를 연결하는 것에 대한 내용입니다.

 

nodejs express 프로젝트 생성하는 방법은

아래 배너를 남겨드리니

해당 포스팅에 가서 프로젝트 생성을 하신 후

db 연결하는 것을 확인해주세요.

 

 

nodejs express 프로젝트 생성 (feat.macos)

안녕하세요. 터미네입니다. 이번 포스팅에서는 nodejs express 프로젝트 생성해보겠습니다. IntelliJ를 사용해서 nodejs express 프로젝트를 실행해보겠습니다. 우선 nodejs는 다들 설치 하셨죠? nodejs 설치

danbam.asbai.xyz

 

제가 연결할 db는 mysql db이고

knex 라이브러리를 사용할 것입니다.

 

mysql db가 pc에 설치되어있지 않으시면

아래 배너를 남겨드리니 포스팅 확인을 통해 설치하시고

이어서 내용 확인해주세요.

 

 

macos Mysql 설치하기

안녕하세요. 터미네입니다. 이번 포스팅은 Mac OS 전용으로 쓴 포스팅입니다. 윈도우에서의 Mysql 설치방법은 별도로 포스팅 하고 안내해드리겠습니다. brew가 설치가 되어있지 않으시면, 아래 포스

danbam.asbai.xyz

 

knex 설치는 아래와 같이 합니다.

그리고 mysql 및 lodash 라이브러리 등등을 같이 설치합니다.

 

$ npm install knex  => 버전 0.21.21

$ npm install mysql => 버전 2.18.1

$ npm install lodash => 버전 4.17.21

$ npm install bookshelf => 버전 1.2.0

$ npm install cors => 버전 2.8.5

 

knex가 설치 되셨으면,

first-nodejs-express 프로젝트에

config 디렉토리와

config 디렉토리 안에 index.js 파일을 생성합니다.

config 디렉토리 및 하위 파일 index.js

 

model 디렉토리를 생성한 후

index.js , knex.js 파일을 생성 해주세요.

 

 routes 디렉토리에

public 디렉토리를 만드신 후 checkConnectMysqlDB.js 파일을 생성해주세요.

 

마지막으로 app.local.js 파일을 만들어주시면 되는데

app.js와 동일한 디렉토리에 만들어 주시면 됩니다.

 

차례대로 디렉토리 및 파일을 만드셨으면

아래 이미지처럼 되셨을 거에요.

 

 

 

디렉토리 및 파일 생성 후 최종 결과

 

만든 파일의 소스를 공개하면 아래와 같습니다.

 

# package.json
{
  "name": "first-nodejs-express",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node app.local.js" //명령어 npm run start 또는 yarn run start
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "cors": "2.8.5",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "knex": "0.21.21",
    "lodash": "4.17.21",
    "morgan": "~1.9.1",
    "mysql": "2.18.1",
    "bookshelf": "1.2.0",
    "pug": "2.0.0-beta11"
  }
}
# config/index.js
'use strict';
const _ = require('lodash')
const stage = process.env.stage || process.env.NODE_ENV || 'default'
console.log(stage)
let config = {
    default: {
        database: {
            client: 'mysql',
            connection: {
                timezone: 'Z',
                host : 'localhost',
                user : 'test',
                password : 'test',
                database : 'test'
            },
            debug: true,
            pool: { min: 0, max: 1 }
        },
    },
}
config[stage].stage = config[stage].env = stage
module.exports = _.assign(config.default, config[stage]);
# model/index.js
'use strict'
const _ = require('lodash')
const Bookshelf = require('bookshelf')
const knex = require('./knex')

const bookshelf = module.exports = Bookshelf(knex);
# model/knex.js
'use strict'
const knex = require('knex')
const config = require('../config')

module.exports = knex(config.database)

 

# checkConnectMysqlDB.js
'use strict'
const express = require('express')
const bookshelf = require('../../model')
const db = bookshelf.knex
const router = module.exports = express.Router()
router.path = '/public/checkConnectMysqlDB'

router.get('/select', async(req, res)=>{
    console.log('mysql 데이터 조회');
    let output;
    try{
        output = await db('test') //mysql에 test 테이블을 미리 생성
        console.log(JSON.stringify(output))
    }catch(e){
        console.log(e);
    }
    res.send({
        output
    });
})
# app.js
const _ = require('lodash')
const express = require('express')
const config = require('./config')

const app = module.exports = express()
app.set('view engine', 'pug')

app.use(require('cors')())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

const routers = [
  '/public/checkConnectMysqlDB'
]
routers.forEach(path => {
  app.use(path, require('./routes' + path))
  console.log(path)
})
# app.local.js
const app = require('./app')

app.listen(3000, e => {
  if (e) return console.error(e)
  
  console.log('Listen port 3000')
})

 

차례대로 잘 하셨으면

intellij 터미널에 가셔서

nodejs 서버를 실행해봐야겠죠?

 

$ npm run start

위 명령어가 정상적으로 실행되면 아래와 같이 화면이 뜰 것입니다.

nodejs 로컬 서버 구동

마지막 단계가 남았습니다.

mysql DB에 접속하셔서

test 라는 테이블을 생성하시고

 

컬럼은 username, age 각각 varchar(10)으로 

만들신 후에

 

아무 데이터나 insert를 해보세요.

 

create table test
(
	username varchar(10) not null comment '유저이름',
	age varchar(10) not null comment '나이'
) default character set utf8 collate utf8_general_ci;

insert into test (username, age) values ('터미네', '99');

 

자 이제 결과를 확인해봐야겠죠.

아래 url로 접속하면 결과를 확인하실 수 있습니다.

 

http://localhost:3000/public/checkConnectMysqlDB/select

nodejs express mysql db 연결 확인 최종결과물

 

여기까지 따라오시느라 정말 고생 많으셨습니다.

 

가장 기본적이고 기초적인 포스팅이 모두 끝나면

조금 더 복잡하고 실무에 근접한 포스팅을 할 예정인데

 

그 때에는 깃허브 링크를 남겨서

일일이 타이핑하는 수고를 없애겠습니다.

 

감사합니다.

 

728x90
반응형