[Express] req.query / req.params / req.body

챔수·2023년 4월 7일
0

개발 공부

목록 보기
38/101

URL에서의 명칭

http://a.com:3000/main?id=1&name=kim

  • http : protocol
  • a.com : host(domain)
  • 3000 : port
  • main : path
  • id=1&name=kim : query string

1. req.params

예시로 /:id/:name 경로가 있다면 :id속성과 :name속성을 req.params.id, req.pareams.name으로 사용할 수 있다.

// 요청온 url : http://a.com:3000/main/100/jun 이 들어왔을때 
router.get('/:id/:name', (req, res, next) => {

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

2. req.query

Express의 request에 들어오는 값에는 URL이 들어 온다. 이 URL값의 query string 값을 가져오고 싶으면 req.query를 사용하면 된다. req.query 에서 req부분은 매개변수명이기 때문에 어떤식으로든 바뀔 수 있다. 보통 req, request를 사용한다.

// 요청온 url : http://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!' }
});

3. req.body

JSON 같은 데이터의 body 데이터를 담을때 사용한다. 주로 post로 유저의 정보 또는 파일 업로드를 보냈을때 사용하고 요청 본문에 제출된 키 - 값의 데이터 형태로 된다.

클라이언트

// 클라이언트 단에서, 자바스크립트로 get요청을 보냄

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

// 방식 2
await axios({
  method: "post",
  url: `www.example.com/post/1/jun`,
  data: { // post 로 보낼 데이터
  	name: 'kim',
    age: 11
  },
})

서버

app.use(express.json()); // json 형식 폼 요청 들어오면 파싱

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

  // ../100/jun 부분이 담기게 된다.
  console.log(req.params) // { id: '100', name: 'jun' }
  
  // post보낼때 담은 객체 부분이 담기게 된다.
  console.log(req.body) // { name: 'kim', age: 11}
  
});
profile
프론트앤드 공부중인 챔수입니다.

0개의 댓글