본문 바로가기
Node.js

Express request(req.params, req.query, req.body)

by devved 2022. 10. 3.
반응형

express에서 request란?

'HTTP request'로써 'req'로 표현되는 객체
request 'query string', 'parameters, 'body', 'HTTP header' 등의 프로퍼티를 가진다

위와 같이 ‘req’객체에는 다양한 프로퍼티가 있지만, 오늘은 req.params와 req.query에 대하여 알아보려한다.

 

req.params

라우터 매개변수

// 예시 1
// 제품별 상세 페이지 routes부분 :productId을 예약어로 지정하여 -> req.params.productId로 받을 수 있게함
router.get('/products/:productId', shopController.getProduct);

// controller 부분 
exports.getProduct = (req, res, next) => {
  const prodId = req.params.productId;
  // routes에서 /products/:productId 지정해줬기 때문에 params에서 사용가능
  Product.findById(prodId, product => {
    // 불러온 제품의 세부 정보
    res.render('shop/product-detail', {
      product: product, 
      pageTitle: product.title, 
      path: '/products'
    });
  })
}

// 예시 2 
// 요청온 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

req.query는 해당 라우트 경로에서 각각의 'query string'을 파라미터로 갖는 객체 프로퍼티
만약 'query parser'가 값이 없으면 빈 객체가 나올 것이고, 그렇지 않으면 해당에 맞는 'query parser'가 나올 것.

클라이언트

// 요청 방식 
// 클라이언트 단에서, 자바스크립트로 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!' },
})

 

서버

// 서버 사용 방식
app.use(express.urlencoded({ extended: false })); // uri 방식 폼 요청 들어오면 파싱

// GET /search?q=tobi+ferret
console.dir(req.query.q)
// '/search'라는 라우트 경로에서 query.q에 해당하는 값은 'tobi ferret'
// => 'tobi ferret'

// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
console.dir(req.query.order)
// '/shoes'라는 라우트 경로에서 query.order에 해당하는 값은 'desc'
// => 'desc'

console.dir(req.query.shoe.color)
// '/shoes'라는 라우트 경로에서 query.shoe.color에 해당하는 값은 'blue'
// => 'blue'

console.dir(req.query.shoe.type)
// '/shoes'라는 라우트 경로에서 query.shoe.type에 해당하는 값은 'converse'
// => 'converse'

💡 req.query의 형태는 사용자의 임의에 따라 결정되므로 그 해당 객체의 프로퍼티와 값을 신뢰하기 전에 타당한 것인지 입증되어야 한다. 예를 들어 'req.query.foo.toString()'은 여러 이유에서 입증이 실패될 수 있다. 'foo'가 없을 수도 있고 string이 아닐 수도 있으며, toString'은 function이 아닌 string일 수 있는 것이다.

 

req.body

'request body'에 'key-value'의 데이터가 담긴 객체 프로퍼티 JSON 객체에 접근 가능 주로 POST로 유저의 정보 또는 파일 업로드(formdata)를 보냈을 때 사용

클라이언트

// 클라이언트 단에서, 자바스크립트로 get요청을 보냄
await axios({
  method: "post",
  url: `www.example.com/user`,
  data: { // post 로 보낼 데이터
  	name: 'nomad',
    age: 11,
    married: true
  },
})

서버

app.use(express.json()); // json 형식 폼 요청 들어오면 파싱
 
// 요청온 url : www.example.com/user
router.post('/user', (req, res, next) => {
  console.log(req.body) // { name: 'nomad', age: 11, married: true }
});

 

Reference

https://inpa.tistory.com/entry/EXPRESS-📚-reqparams-reqquery-reqbody-🤔-정리

https://velog.io/@aaronddy/Express-req.params-vs.-req.body

반응형