Request & Response
- Request
클라이언트가 서버에게 전달하려는 정보나 메시지를 담는 객체- Response
서버에서 클라이언트로 응답 메시지를 전송시켜주는 객체
req 객체
app.use(express.json());
// req.body를 사용하기 위한 미들웨어
(전역 미들웨어에 적용)
express.json()
Middleware를 이용하여야 해당 객체 사용 가능app.post("/",(req, res) => {
console.log(req.body);
res.send("기본 URI에 POST 메소드가 정상적으로 실행되었습니다.");
});
// C:\Users\sec\Desktop\sparta\SPA_MALL>node app
// 3000 포트로 서버가 열렸어요!
// { key1234: '안녕하세요 key1234입니다.' }
BODY > JSON
{
"key1234": "안녕하세요 key1234입니다."
}
app.get("/:id",(req, res) => {
console.log(req.params);
res.send(":id URI에 정상적으로 반환되었습니다.");
});
// C:\Users\sec\Desktop\sparta\SPA_MALL>node app
// 3000 포트로 서버가 열렸어요!
// { id: 'helloworld' } => localhost:3000/helloworld
app.get("/",(req, res) => {
console.log(req.query);
res.send('정상적으로 반환되었습니다.');
});
// C:\Users\sec\Desktop\sparta\SPA_MALL>node app
// 3000 포트로 서버가 열렸어요!
// { queryKey: 'valuevalue' }
res 객체
app.get("/",(req, res) => {
console.log(req.query);
res.status(400).json({
"keykey" : "value 입니다.",
"이름입니다." : "이름일까요?",
});
});
//status: 400 Bad Request
res.send(데이터)
데이터를 포함하여 Response를 전달
res.json(JSON)
JSON 형식으로 Response를 전달
i) 첫 번째 방법
app.get("/",(req, res) => {
console.log(req.query);
const obj = {
"keykey" : "value 입니다.",
"이름입니다." : "이름일까요?",
}
res.json(obj)
});
ii) 두 번째 방법
app.get("/",(req, res) => {
console.log(req.query);
res.json ({
"keykey" : "value 입니다.",
"이름입니다." : "이름일까요?",
});
});