Request 객체는 API를 컨트롤하기 위한 메소드를 담고 있다.
총 세가지가 있다.
라우터 매개변수
예를 들어 /: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' }
});
경로의 각 퀴리 문자열 매개 변수에 대한 속성이 포함 된 개체다. (주로 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!' }
});
// 클라이언트 단에서, 자바스크립트로 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 }
});