[express] req.params, req.query, req.body

jm4293·2023년 2월 6일
0

req.params

url: www.example.com/public/100/jun

router.get('/:id/:name', (req, res, next) => {
console.log(req.params) // { id: '100', name: 'jun' }
});

req.query

url: www.example.com/post/1/jun?title=hello

// 클라이언트
// 방식 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 방식 폼 요청 들어오면 파싱
 
router.get('/:id/:name', (req, res, next) => {
 
console.log(req.params) // { id: '100', name: 'jun' }
console.log(req.query) // { title : 'hello!' }
});

req.body

url:

// 클라이언트
// 방식 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) => {
 
console.log(req.params) // { id: '100', name: 'jun' }
console.log(req.body) // { name: 'nomad', age: 11, married: true }
});
profile
FE | Node.js Developer

0개의 댓글