백엔드/Node.js

[Node.js] MySQL 연동

개발찾아 삼만리 2024. 11. 8. 10:09

MySQL

💡 MySQL은 오픈 소스의 관계형 데이터베이스 관리 시스템(RDBMS)이다.

 

1. MySQL 설치

npm install mysql

package.json에 성공적으로 추가

// index.js
console.log("Hello world");
npm start

콘솔에 "Hello world"가 출력되는 것을 확인할 수 있다.

 

2. 테이블 생성 및 테스트용 데이터 삽입

MySQL에 접속해 테이블을 생성하고 테스트용 데이터를 삽입한다.

터미널을 이용해 해당 위치 /usr/local/mysql/bin에서 진행했다.

// mysql 실행
./mysql -u root -p
CREATE DATABASE IF NOT EXISTS my_db;

USE my_db;

CREATE TABLE IF NOT EXISTS Users (
  id VARCHAR(45) NOT NULL,
  password VARCHAR(45) NOT NULL,
  PRIMARY KEY (id));

INSERT INTO Users (id, password) VALUES ('tjddnr9553', '1234');

SELECT password FROM Users WHERE id='tjddnr9553';

데이터가 성공적으로 들어감

 

3. Node.js와 MySQL 연동

const mysql      = require('mysql');
const connection = mysql.createConnection({
  host     : 'localhost',
  user     : '< MySQL username >',
  password : '< MySQL password >',
  database : 'my_db'
});

connection.connect();

connection.query('SELECT * from Users', (error, rows, fields) => {
  if (error) throw error;
  console.log('User info is: ', rows);
});

connection.end();

Node.js와 MySQL 연동 성공

만약 'ER_NOT_SUPPORTED_AUTH_MODE' 에러가 발생하면 아래의 sql을 실행하고 다시 접속한다.

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '< MySQL password >';
FLUSH PRIVILEGES;

 

4. Route 작성

클라이언트 요청에 대응하는 route를 설정한다.

const express    = require('express');
const mysql      = require('mysql');
const dbconfig   = require('./config/database.js');
const connection = mysql.createConnection(dbconfig);

const app = express();

// 포트 번호 세팅
app.set('port', process.env.PORT || 3000);

app.get('/', (req, res) => {
  res.send('Root');
});

// 해당 주소로 get 요청이 들어오면 실행
app.get('/users', (req, res) => {
  connection.query('SELECT * from Users', (error, rows) => {
    if (error) throw error;
    console.log('User info is: ', rows);
    res.send(rows);
  });
});

app.listen(app.get('port'), () => {
  console.log('Express server listening on port ' + app.get('port'));
});

데이터베이스 설정 정보를 아래와 같이 작성한 후 루트 디렉터리 아래 config 디렉터리에 저장한다.

// config/database.js
module.exports = {
  host     : 'localhost',
  user     : '< MySQL username >',
  password : '< MySQL password >',
  database : 'my_db'
};

서버를 실행하고 http://localhost:3000/users에 접속해 결과를 확인한다.

API 요청 응답 성공

 

Reference
Node.js(Express)와 MySQL 연동