Request

ujin·2022년 11월 20일
0

CS

목록 보기
2/3

Request 객체는 API를 컨트롤하기 위한 메소드를 담고 있다.

  • params
  • query
  • body

총 세가지가 있다.

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.examle.com/post/1/jun?title=hello! 이면, title 매개변수의 hello!이라는 값(argument)을 가져온다.

클라이언트

// 클라이언트 단에서, 자바스크립트로 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로 유저의 정보 또는 파일 업로드를 보냈을 때 요청 본문에 제출된 키-값 데이터 쌍을 포함한다.

클라이언트

// 클라이언트 단에서, 자바스크립트로 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개의 댓글