URL에서의 명칭
예시로 /: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' }
});
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!' }
});
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}
});