개발하고 싶은 초심자
3-2. 220515 코드작성(2) & 에러 핸들링 본문
1. npm start로 서버 실행 시 나왔던 에러 핸들링
config.json을 불러올 수 없어 나오는 에러로, dotenv를 활용하여 json 파일을 js로 바꿔주는 작업을 했다.
models/index.js에서 바꿔준 코드
before
const config = require('../config')[process.env.NODE_ENV];
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
}
after
const config = require('../config/config')[process.env.NODE_ENV];
let sequelize;
sequelize = new sequelize (
config.database,
config.username,
config.password,
config
);
이렇게 바꾸어줬더니 config 에러는 해결되었는데 바로 다음과 같은 에러 메시지가 떴다.
database를 읽어올 수 없다는 타입 에러 메시지다.
new sequelize안에서 database의 위치를 옮겨주었더니, 처음에 나오는 인자들은 전부 읽어올 수 없다고 나온다.
즉, 에러 메시지 안의 database에서 username이나 password로 뜨는 형식이다.
models/index.js에서
console.log(require('../config/config'), env);
콘솔을 찍어 제대로 된 콘솔값이 나오는지 확인했을 때 config.js가 잘 나오는 것을 확인할 수 있었다.
일단 models/Users.js와 brewery.js의 seed파일에 더미 데이터를 하나씩 작성해주어 데이터베이스에 삽입해주었다.
sequelize seed 기능 사용 db에 데이터 삽입하기 참고 레퍼런스
그 과정에서 models/index.js 파일의 코드를
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const env = process.env.NODE_ENV || "development";
const basename = path.basename(__filename);
const config = require('../config/config')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
}
이렇게 바꿔줬다.
일단 config.database가 undefined상태가 되는 에러를 해결했다.
또한 데이터를 삽입하는 과정에서 npx sequelize-cli db:seed:all 명령어를 실행했을 때
default value를 설정하라는 오류가 나왔다.
그래서 seed파일 내에 createdAt과 updatedAt 필드값을 설정하고 다시 시도했더니 성공적으로 이루어졌다.
그러고 나서 다시 npm start를 했더니 이번에는 다른 에러가 나왔다.
마이그레이션을 해주고 그에 맞는 시드 파일을 생성했다.
npx sequelize-cli seed:generate --name <시드파일이름>
db[model.name] = model; 로 코드를 바꿔주었더니 이번에는 다음과 같은 에러가 나온다.
'name'을 읽어올 수 없다는 타입 에러가 떴다.
왜...(해결을 하지 못했다...다음 날로 밀렸다...)
'Project in Codestates > First Project' 카테고리의 다른 글
3-4. sequelize.sync()를 활용하여 모든 모델 자동 동기화하기 (0) | 2022.05.17 |
---|---|
3-3. 220516 처음부터 다시 시작, 에러 핸들링 & oauth 활용 (0) | 2022.05.16 |
3-1. 220514 코드 작성(2) (0) | 2022.05.13 |
3. 220513 코드 작성(1) (0) | 2022.05.13 |
2-4. 220512 Git Flow 연습 (0) | 2022.05.12 |