Status code
브라우저에서 같은 아이디/이메일을 보내면 이미 있는 아이디/이메일이라고 뜨지만
브라우저 창에 아이디와 비밀번호를 저장 할 것이냐고 묻는다
logger을 보면 POST/200이 뜨는데 이는 OK라는 뜻이고 이걸 보고 작동한거다 따라서
브라우저는 상태코드를 보내지않으면 에러가난건지 아닌지 알 수 없음 !
if (password !== password2) {
return res.status(400).render("join", {
pageTitle,
errorMessage: "Password confirmation does not match."
});
}
if (exists) {
return res.status(400).render("join", {
pageTitle,
errorMessage: "This username/email is already taken.",
})
}
videoController에도
export const postUpload = async (req, res) => {
const { title, description, hashtags } = req.body;
try {
await Video.create({
title,
description,
hashtags: Video.formatHashtags(hashtags),
});
return res.redirect("/");
} catch (error) {
console.log(error);
return res.status(400).render("upload", {
pageTitle: "Upload video",
errorMessage: error._message,
});
}
}
export const watch = async (req, res) => {
const { id } = req.params;
const video = await Video.findById(id);
if (!video) {
return res.status(404).render("404", { pageTitle: "Video not found" });
}
return res.render("watch", { pageTitle: video.title, video });
}
export const postEdit = async (req, res) => {
const { id } = req.params;
const { title, description, hashtags } = req.body;
const video = await Video.exist({ _id: id });
if (!video) {
return res.status(404).render("404", { pageTitle: "Video not found" })
}
외에도 곳곳 필요한 곳에
await Video.findByIdAndUpdate(id, {
title,
description,
hashtags: Video.formatHashtags(hashtags),
})
return res.redirect(`/videos/${id}`);
}
[상태코드]
https://ko.wikipedia.org/wiki/HTTP_%EC%83%81%ED%83%9C_%EC%BD%94%EB%93%9C
- 200(OK): 서버가 요청을 제대로 처리했다는 뜻이다. 이는 주로 서버가 요청한 페이지를 제공했다는 의미로 쓰인다.
- 400(Bad Request): 서버가 요청의 구문을 인식하지 못할 때 발생한다. 클라이언트 측에서 문제가 있을 때 주로 발생한다.
- 404(Not Found): 서버가 요청한 페이지를 찾을 수 없을 때 발생한다. 서버에 존재하지 않는 페이지에 대한 요청이 있을 경우 서버는 이 코드를 제공한다.
기존코드에 try catch 추가함
try catch 문 사용하면 기존에 적은 에러말고도 에러 잡아 낼 수있음
직접 에러를 처리하고 난 다음에 적어야함
export const postJoin = async (req, res) => {
console.log(req.body);
const { name, username, email, password, password2, location } = req.body;
const exists = await User.exists({ $or: [{ username }, { email }] });
const pageTitle = "Join";
if (password !== password2) {
return res.status(400).render("join", {
pageTitle,
errorMessage: "Password confirmation does not match."
});
}
if (exists) {
return res.status(400).render("join", {
pageTitle,
errorMessage: "This username/email is already taken.",
})
}
try {
await User.create(
{
name,
username,
email,
password,
location
}
);
return res.redirect("/login");
} catch (error) {
return res.status(4000).render("join", {
pageTitle: "Join",
errorMessage: error._message,
});
}
Login 관련 템플릿,컨트롤러,라우터 정리
postLogin에서 해야하는일
username을 가진 User있는지확인
비밀번호 맞는지확인
export const postLogin = async (req, res) => {
const { username, password } = req.body;
const exists = await User.exists({ username });
if (!exists) {
return res.status(400).render("login", {
pageTitle: "Login",
errorMessage: "An account with this username does not exists"
});
}
// check if account exist
//check if password correct
res.end();
}
Controller 중 가장 중요한건 post
get은 단순 렌더링만 하지만
데이터를 다루고 에러처리, 유효성 체크 등을 하면서 DB와 통신하고 있어서
//check if password correct
bycrpt 이용 할 것임 npm i bycrpt
bcrypt.compare 하기전에
유저가 로그인하려는 계정이 필요하다.
object정보가 필요
const user = await User.findOne(username);
위에 const exists = await User.exists(username);이이있음
중복되니 한개만
export const postLogin = async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user) {
return res.status(400).render("login", {
pageTitle: "Login",
errorMessage: "An account with this username does not exists"
});
}
console.log(user.password);
res.end();
}
1.import bcrypt from "bcrypt";
export const postLogin = async (req, res) => {
const { username, password } = req.body;
const pageTtitle = "Login";
const user = await User.findOne({ username });
if (!user) {
return res.status(400).render("login", {
pageTitle,
errorMessage: "An account with this username does not exists"
});
}
const ok = await bcrypt.compare(password, user.password);
if (!ok) {
return res.status(400).render("login", {
pageTitle,
errorMessage: "Wrong password",
});
}
res.end();
}