노드 입문_9

·2022년 12월 13일
0

Request & Response

  • Request
    클라이언트가 서버에게 전달하려는 정보나 메시지를 담는 객체
  • Response
    서버에서 클라이언트로 응답 메시지를 전송시켜주는 객체

서버 모듈

  • Node.js 서버 모듈에는 http 모듈과 Express 모듈이 존재
  • http 확장형 => Express
  • http는 잘 사용 x

Express 모듈의 req, res 객체

req 객체

app.use(express.json());
// req.body를 사용하기 위한 미들웨어
(전역 미들웨어에 적용)

  • req.body
    Request를 호출할 때 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입니다."
}
  • req.params
    라우터 매개 변수에 대한 정보가 담긴 객체
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
  • req.query
    Request를 호출할 때 쿼리 스트링으로 전달된 정보가 담긴 객체
app.get("/",(req, res) => {
    console.log(req.query);

    res.send('정상적으로 반환되었습니다.');
});

// C:\Users\sec\Desktop\sparta\SPA_MALL>node app
// 3000 포트로 서버가 열렸어요!
// { queryKey: 'valuevalue' }

res 객체

  • res.status(코드)
    Response에 HTTP 상태 코드를 지정
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 입니다.",
        "이름입니다." : "이름일까요?",
    });
});
profile
개발자가 되는 과정

0개의 댓글