MySQL 데이터베이스 연결 후 코드 실행(npm start) 시 Error 발생
/Users/jaehyeon/Desktop/Dwitter/server/node_modules/mysql2/lib/packets/packet.js:728
const err = new Error(message);
^
Error: Access denied for user 'root'@'localhost' (using password: YES)
at Packet.asError (/Users/jaehyeon/Desktop/Dwitter/server/node_modules/mysql2/lib/packets/packet.js:728:17)
at ClientHandshake.execute (/Users/jaehyeon/Desktop/Dwitter/server/node_modules/mysql2/lib/commands/command.js:29:26)
at PoolConnection.handlePacket (/Users/jaehyeon/Desktop/Dwitter/server/node_modules/mysql2/lib/connection.js:456:32)
at PacketParser.onPacket (/Users/jaehyeon/Desktop/Dwitter/server/node_modules/mysql2/lib/connection.js:85:12)
at PacketParser.executeStart (/Users/jaehyeon/Desktop/Dwitter/server/node_modules/mysql2/lib/packet_parser.js:75:16)
at Socket.<anonymous> (/Users/jaehyeon/Desktop/Dwitter/server/node_modules/mysql2/lib/connection.js:92:25)
at Socket.emit (node:events:390:28)
at Socket.emit (node:domain:475:12)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9) {
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user 'root'@'localhost' (using password: YES)",
sql: undefined
}
📌 db/database.js
import mysql from 'mysql2';
import { config } from '../config.js';
// mysql 접속
const pool = mysql.createPool({
host: config.db.host,
user: config.db.user,
database: config.db.database,
password: config.db.passowrd,
});
// 비동기 사용, promise 반환
export const db = pool.promise();
📌 config.js
import dotenv from 'dotenv';
dotenv.config();
function required(key, defaultValue = undefined) {
const value = process.env[key] || defaultValue;
// null, undefined 일 때 true
if (value == null) {
throw new Error(`Key ${key} is undefined`);
}
return value;
}
export const config = {
jwt: {
secretKey: required('JWT_SECRET'),
expiresInSec: parseInt(required('JWT_EXPIRES_SEC', 86400)),
},
bcrypt: {
saltRounds: parseInt(required('BCRYPT_SALT_ROUNDS', 12)),
},
host: {
port: parseInt(required('HOST_PORT', 8080)),
},
db: {
host: required('DB_HOST'),
port: required('DB_PORT'),
user: required('DB_USER'),
database: required('DB_DATABASE'),
passowrd: required('DB_PASSWORD'),
}
}
📌 .env
JWT_SECRET=F2dN7x8HVzBWaQuEEDnhsvHXRWqAR63z
JWT_EXPIRES_SEC=86400
BCRYPT_SALT_ROUNDS=12
DB_HOST=localhost
DB_USER=root
DB_DATABASE=dwitter
DB_PASSWORD=woGUS4996!#
DB_PORT=3306
코드 상에서는 문제가 없다
정상적으로 로그인이 된다.
import mysql from 'mysql2';
import { config } from '../config.js';
// mysql 접속
const pool = mysql.createPool({
host: config.db.host,
user: config.db.user,
database: config.db.database,
password: 'woGUS4996!#',
});
// 비동기 사용, promise 반환
export const db = pool.promise();