[TIL] req.params/query/body

Manta·2024년 9월 9일
0

TIL

목록 보기
5/19

req.params란?

  • 라우터의 매개변수
  • 예를 들어 /:id/:name 경로가 있으면 ":id"속성과 ":name"속성을 req.params.id, req.params.name으로 사용할 수 있다.
    www.example.com/post/1/jun 일 경우 1과 jun을 받는다. 
// 요청온 url : www.example.com/public/100/jun
router.get('/:id/:name', (req, res, next) => {

  //../100/jun 부분이 담기게 된다.
  console.log(req.params) // { id: '100', name: 'jun' }
});

req.query

  • 경로의 각 쿼리 문자열 매개 변수에 대한 속성이 포함 된 개체다. (주로 GET 요청에 대한 처리)
  • 예를 들어 www.example.com/post/1/jun?title=hello! 이면, title=hello! 부분을 객체로 매개변수의 값을 가져온다.
// 클라이언트 단에서, 자바스크립트로 get요청을 보냄

// 방식 1
await axios.get(`www.example.com/post/1/jun?title=hello!`)

// 방식 2
await axios({
  method: "get",
  url: `www.example.com/post/1/jun`,
  params: { title: 'hello!' },
})
// 요청온 url : www.example.com/public/100/jun?title=hello!
app.use(express.urlencoded({ extended: false })); // uri 방식 폼 요청 들어오면 파싱

router.get('/:id/:name', (req, res, next) => {

  //../100/jun 부분이 담기게 된다.
  console.log(req.params) // { id: '100', name: 'jun' }
  
  // title=hello! 부분이 담기게 된다.
  console.log(req.query) // { title : 'hello!' }
});

req.body

  • JSON 등의 바디 데이터를 담을때 사용한다.
  • 주로 POST로 유저의 정보 또는 파일 업로드(formdata)를 보냈을 때 사용
  • 요청 본문에 제출 된 키-값 데이터 쌍을 포함한다.
// 클라이언트 단에서, 자바스크립트로 get요청을 보냄

// 방식 1
await axios.post('www.example.com/post/1/jun', { 
    name: 'nomad', // post 로 보낼 데이터
    age: 11,
    married: true
});

// 방식 2
await axios({
  method: "post",
  url: `www.example.com/post/1/jun`,
  data: { // post 로 보낼 데이터
  	name: 'nomad',
    age: 11,
    married: true
  },
})
app.use(express.json()); // json 형식 폼 요청 들어오면 파싱

// 요청온 url : www.example.com/public/100/jun
router.post('/:id/:name', (req, res, next) => {

  // public/100 부분이 담기게 된다.
  console.log(req.params) // { id: '100', name: 'jun' }
  
  // post보낼때 담은 객체 부분이 담기게 된다.
  console.log(req.body) // { name: 'nomad', age: 11, married: true }
  
});
profile
공부할게 너무 만타🫠

0개의 댓글