MySQL 연결하기
시퀄라이즈를 통해 익스프레스 앱과 MySQL을 연결해야 합니다. app.js를 생성하고 익스프레스와 시퀄라이즈 연결 코드를 작성합니다.
const express = require("express");
const path = require("path");
const morgan = require("morgan");
const nunjucks = require("nunjucks");
const { sequelize } = require("./models");
const app = express();
app.set("port", process.env.PORT || 3001);
app.set("view engine", "html");
nunjucks.configure("views", {
express: app,
watch: true,
});
sequelize
.sync({ force: false })
.then(() => {
console.log("데이터베이스 연결 성공");
})
.catch((err) => {
console.error(err);
});
app.use(morgan("dev"));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use((req, res, next) => {
const error = new Error(`${req.method} ${req.url} 라우터가 없습니다.`);
error.status = 404;
next(error);
});
app.use((err, req, res, next) => {
res.locals.message = err.message;
res.locals.error = process.env.NODE_ENV !== "production" ? err : {};
res.status(err.status || 500);
res.render("error");
});
app.listen(app.get("port"), () => {
console.log(app.get("port"), "번 포트에서 대기 중");
});
require('./models')는 require('./models/index.js')와 같습니다. 폴더 내의 index.js 파일은 require할 때 이름을 생략할 수 있습니다. db.sequelize를 불러와서 sync 메서드를 사용해 서버를 실행할 때 MySQL과 연동되도록 했습니다. 내부에 force: false 옵션이 있는데, 이 옵션을 true로 설정하면 서버를 실행할 때마다 테이블을 재생성합니다. 테이블을 잘못 만든 경우에 true로 설정하면 됩니다.
MySQL과 연동할 때는 config 폴더 안의 config.json 정보가 사용됩니다. 다음과 같이 수정합니다. 자동으로 생성한 config.json에 operatorAliases 속성이 들어 있다면 삭제합니다.
config/config.json
{
"development": {
"username": "root",
"password": "1234",
"database": "nodejs",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
development.password와 development.database를 현재 MySQL 커넥션과 일치하게 수정하면 됩니다. test와 production 쪽은 각각 테스트 용도와 배포 용도로 접속하기 위해 사용되는 것이므로 여기서는 설정하지 않습니다.
password 속성에는 여러분의 MySQL 비밀번호를 입력하고, database 속성에는 nodejs를 입력하세요.
이 설정은 process.env.NODE_ENV가 development일 때 적용됩니다(기본적으로 development입니다). 나중에 배포할 때는 process.env.NODE_ENV를 production으로 설정해둡니다. 따라서 배포 환경을 위해 데이터베이스를 설정할 때는 config/config.json의 production 속성을 수정하면 됩니다. 마찬가지로 테스트 환경(process.env.NODE_ENV가 test)일 때는 test 속성을 수정합니다.
npm start로 서버를 실행하면 3001번 포트에서 서버가 돌아갑니다. 라우터를 만들지 않았기에 실제로 접속할 수는 없지만 다음과 같은 로그가 뜹니다.
콘솔
$ npm start
> learn-sequelize@0.0.1 start
> nodemon app
[nodemon] 3.1.10
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node app.js`
3001 번 포트에서 대기 중
Executing (default): SELECT 1+1 AS result
데이터베이스 연결 성공
마지막 두 로그가 뜨면 연결이 성공한 것입니다. 연결에 실패한 경우 에러 메시지가 로깅됩니다. 에러는 주로 MySQL 데이터베이스를 실행하지 않았거나(Error: connect ECONNREFUSED 127.0.0.1:3306), 비밀번호가 틀렸거나(Error: Access denied for user 'root'@'localhost' (using password: YES)), 존재하지 않는 데이터베이스를 적었을 때(Error: Unknown database) 발생합니다.
'프로그래밍 언어 > NODE JS' 카테고리의 다른 글
| 관계 정의하기 (1) | 2025.08.30 |
|---|---|
| 모델 정의하기 (1) | 2025.08.27 |
| 시퀄라이즈 사용하기 (0) | 2025.08.21 |
| CRUD 작업하기 (1) | 2025.08.18 |
| 데이터베이스 및 테이블 생성하기 (6) | 2025.08.15 |