express: what is the difference between req.query and req.body

后端 未结 2 1645
梦如初夏
梦如初夏 2021-02-06 13:31

I want to know what is the difference between req.query and req.body?

below is a piece of code where req.query is used. what happens if i use req.body

2条回答
  •  轮回少年
    2021-02-06 13:37

    req.body is mainly used with form using POST method. You've to use enctype="application/x-www-form-urlencoded" in the form properties. As POST method don't show anything in URL, you have to use body-parser middleware if the form contains an input text with name="age" then req.body.age return the value of this feld.

    req.query takes parameters in the URL (mainly GET method) example for this URL ► http://localhost/books?author=Asimov app.get('/books/', (req, res) => { console.log(req.query.author) } will return Asimov

    by the way, req.params take the end part of the URL as a parameter. example for this URL ► http://localhost/books/14 app.get('/books/:id', (req, res) => { console.log(req.params.id) } will return 14

提交回复
热议问题