-
카테고리
-
세부 분야
풀스택
-
해결 여부
미해결
회원가입 status 500 findOne 오류
23.10.14 16:40 작성 조회수 156
0
안녕하십니까 제로초님 회원가입 구현 관련 질문드립니다.
강의를 보며 코딩을 하였고 오타도 없는 것을 확인을 했습니다.
그런데 response로 계속 500이 들어오며 findOne 관련 오류가 납니다.. 혹시 해결책을 알수있을까요?
models/user.js
//model은 mysql의 테이블과 같은 개념이다.
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
//여기서 User는 모델이름 => 자동으로 소문자화되고 복수형이 된다. ex)users
"User",
{
//id는 mysql에서 자동으로 넣어주기 때문에 필요없다.
email: {
type: DataTypes.STRING(30),
//STRIN, INTEGER, BOOLEAN, FLOAT, DATATIME 등이 자주 사용된다.
//이메일은 문자열이고 30글자 이내여야한다.
allowNull: false, //false면 필수 -> 무조건 입력해야함.
unique: true, //이메일은 고유한 값이어야함. 중복값이 있으면 안된다.
},
nickname: {
type: DataTypes.STRING(30),
allowNull: false, //false면 필수 -> 무조건 입력해야함.
},
password: {
type: DataTypes.STRING(100),
//비밀번호는 암호화를 하게되면 길이가 늘어나기 때문에 여유있게 100글자
allowNull: false, //false면 필수 -> 무조건 입력해야함.
},
},
{
charset: "utf8",
collate: "utf8_general_ci", //한글 저장
}
);
User.associate = (db) => {
db.User.hasMany(db.Post); //한 사람이 포스트를 여러개 가질 수 있음
db.User.hasMany(db.Comment); //한 사람이 댓글 여러개 가질 수 있음
db.User.belongsToMany(db.Post, { through: "Like", as: "Liked" });
//게시글 좋아요와 유저는 다대다 관계, 중간 테이블으 이름은 Like
db.User.belongsToMany(db.User, {
through: "Follow",
as: "Followers",
foreignKey: "FollowingId",
});
db.User.belongsToMany(db.User, {
through: "Follow",
as: "Followings",
foreignKey: "Followerid",
}); //내가 팔로잉하는 사람을 찾으려면 나를 먼저 찾아야 한다.
};
return User;
};
routes/user.js
const express = require("express");
const { User } = require("../models");
const router = express.Router();
const bcrypt = require("bcrypt");
router.post("/", async (req, res, next) => {
// POST /user/
try {
const exUser = await User.findOne({
where: {
email: req.body.email,
},
});
if (exUser) {
return res.status(403).send("이미 사용 중인 아이디입니다."); //여기서 리턴을 해주지 않으면 밑에 있는 res.json() 과 더불어서 응답이 두번이라 안된다.
}
const hashedPassword = await bcrypt.hash(req.body.password, 12);
await User.create({
//순서를 맞춰주기 위한 Await
//테이블안에 데이터 넣기
email: req.body.email,
nickname: req.body.nickname,
password: hashedPassword, //여기서 req.body가 프론트엔드 Signup에서 보낸 action.data와 같다.
});
res.status(201).send("ok");
} catch (error) {
console.error(error);
next(error); // status 500
}
});
module.exports = router;
back/app.js
const express = require("express");
const cors = require("cors");
const postRouter = require("./routes/post");
const userRouter = require("./routes/user");
const app = express();
const db = require("./models");
db.sequelize
.sync()
.then(() => {
console.log("db 연결 성공");
})
.catch(console.error);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
//여기서 use는 express서버에서 뭔가 장착한다는 뜻
//또한 이 두 문장이 프론트에서 받아온 action.data를 req.body에 넣어준다는 뜻
app.get("/", (req, res) => {
res.send("hello express");
});
app.get("/api", (req, res) => {
res.send("hello api");
});
app.get("/api/posts", (req, res) => {
res.json([
{ id: 1, content: "hello" },
{ id: 2, content: "hello2" },
{ id: 3, content: "hello3" },
]);
});
app.use(
cors({
origin: "*", //모두 허용
credentials: false,
})
);
app.use("/post", postRouter); //"/post"가 중복되므로 앞으로 뽑아줄 수 있다.
app.use("/user", userRouter);
app.listen(3065, () => {
console.log("서버 실행 중");
});
답변을 작성해보세요.
0
답변 1