[React 프로젝트] Node.js와 MySQL 연동 Error

Ma_Seokjae·2023년 2월 2일
post-thumbnail

React 프로젝트를 진행을 하며, Node.js와 MySQL 연동이 계속되지 않는 문제를 겪었습니다. 이런 과정 속에서 마주친 여러 에러들과 해결한 방법에 대해서 정리겸 다루어 보도록 하겠습니다.

연동을 위해 사용 및 작성한 코드

[index.js]

// index.js (실질적으로 server와 database 연결을 위함)
const express = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
const db = require('./config/db')

app.get('/', (req, res)=>{
    console.log('/root');
})

app.get('/login', (req, res)=>{
    console.log('/login')
    db.query("INSERT INTO Course(courseName, Semester) VALUES ('Computer Network', '2주차')", (err, data) => {
        if(!err) {
            console.log(data)
        }
        else {
            console.log(err)
        }
    })
})

app.listen(PORT, ()=>{
    console.log(`Server On : http://localhost:${PORT}`)
})

[db.js]

var mysql = require('mysql');
const db = mysql.createPool({
    host : 'localhost',
    user : 'DB 사용자명',
    password : 'DB 비밀번호',
    database : 'DB 이름'
});

module.exports = db;

[App.js]

// routes
import Router from './routes';
// theme
import ThemeProvider from './theme';
// components
import ScrollToTop from './components/scroll-to-top';
import { StyledChart } from './components/chart';
import { BrowserRouter, Route, Switch } from "react-router-dom";
import axios from 'axios';

// ----------------------------------------------------------------------

export default function App() {
  const selectAll=()=>{
    alert("selectAll!")
    axios.get('/login')
}
  return (
    <ThemeProvider>
    <div>
      <h1>React-Express-MySQL 연결</h1>
      <button onClick={selectAll}>모두 조회</button>
    </div>
      <ScrollToTop />
      <StyledChart />
      <Router />
    </ThemeProvider>
  );
}

추가적으로, [package.json] 파일에 추가

"proxy": "http://localhost:4000",

발생한 error 모음

1. Error: connect ECONNREFUSED ::1:3306

{
  errno: -61,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 3306,
  fatal: true
}

local에서 db를 작성하여 돌려보려고 했는데, 이처럼 connect 자체에 접근 거절 에러가 발생했는데요. 이를 해결하기 위해 terminal로 mysql 접근하여 해당 user에 모든 접근 권한 해제 명령어도 실행해 보았지만, 해결되지 않았습니다…

  • 해결법
    [db.js] 파일에서 host를 아래와 같이 수정

(변경 전)

host : 'localhost',

(변경 후)

host : '127.0.0.1',		// localhost의 ip 주소

둘다 사실상 같은 의미인데, 비유를 하자면, '127.0.0.1'가 본체이고 'localhost'는 본체의 거울이라고 생각하시면 쉽게 이해하실 수 있을 것 같습니다.

이와 같은 문제로 에러가 가끔 발생한다고 한다네요... (혹시 아시는 분... 댓글로 알려주시면 감사하겠습니다...ㅎ)
아무튼, 이렇게 변경을 하니 1번 에러 메시지는 사라졌는데 두번째 에러 메시지가 발생했습니다…

2. Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

이 에러 같은 경우에는 MySQL 패스워드 플러그인 "caching_sha2_password"을 소화하지 못해서 발생하는 오류라고 합니다.

  • 해결법
    terminal로 mysql에 접근한 후 아래 명령어 실행
ALTER USER 'user명'@'host명' IDENTIFIED WITH mysql_native_password BY '설정할 비밀번호';

(변경 전, 플러그인)

caching_sha2_password

(변경 후, 플러그인)

mysql_native_password

플러그인을 다음과 같이 변경을 하면 에러 없이 Node.js와 MySQL이 잘 연동되는 것을 확인할 수 있으실 겁니다. 혹시 플러그인 내용이 잘 변경되었는지 확인하고 싶다면,

mysql> select host, user, plugin, authentication_string from mysql.user;

이 명령어를 terminal로 mysql에 접근하여 실행하면 아래 그림과 같이 잘 변경된 것을 확인할 수 있습니다.

이상 Node.js와 MySQL 연동 Error 해결법을 다룬 Post 마치도록 하겠습니다 :)
(혹시, 잘못된 내용이 있다면 언제든지 댓글로 지적해주시면 정말 감사드리겠습니다!)

profile
Why not change the code?

0개의 댓글