"use strict";
const output = {
home: (req, res) => {
res.render("home/index");
},
login: (req, res) => {
res.render("home/login");
},
};
const users = {
id: ["kim", "park", "choi"],
pw: ["1234", "1q2w3e4r", "iloveyou"],
};
const process = {
login: (req, res) => {
const id = req.body.id,
pw = req.body.pw;
if (users.id.includes(id)) {
const idx = users.id.indexOf(id);
if (users.pw[idx] === pw) {
return res.json({
success: true,
});
}
}
return res.json({
success: false,
msg: "로그인에 실패하셨습니다.",
});
},
};
module.exports = {
output,
process,
};
res.send()
는 send에 전해진 argument에 따라서 Content-type이 자동적으로 만들어진다.res.json()
은 json이 아닌 것도 json형식으로 바꾸어서 보내준다. 즉 content-type 헤더를 application/JSON으로 고정한다. 그런데 결국 res.json()도 마지막에 res.send()를 호출한다.res.end()
는 보내줄 아무 데이터도 없는데 response를 끝내고 싶을때 사용한다.ex) res.status(400).end();"use strict";
const id = document.querySelector("#id"),
pw = document.querySelector("#pw"),
loginBtn = document.querySelector("button");
loginBtn.addEventListener("click", login);
function login() {
const req = {
id: id.value,
pw: pw.value,
};
fetch("/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(req),
})
.then((res) => res.json())
.then(console.log);
}
fetch를 통해 responce를 받을 수 있는데, 이때 반환값은 Promise이므로 .json()으로 변환해주어야 한다. 그리고 이를 console.log에 찍는다.
(.then에서 파라미터로 넘길 값과 실행할 함수의 파라미터가 동일하다면, 함수명만 적는 것으로 생략할 수 있다.)
정상적으로 responce가 도착하는지 확인한다.