Accepting User Data

When our users request a page in our app, their browser issues an HTTP GET request. When they submit a form in our app, the form's method attribute, which is the HTTP method/verb our form should use, determines how their browser will send the form data to our server-side code. We can use the get method like this:

<form action="/greetings" method="get">
<input name="say" value="Hi">
<input name="to" value="Mom">
<button>Send my greetings</button>
</form>

And it will create this HTTP request:

GET /greetings?say=Hi&to=Mom HTTP/1.1
Host: foo.com

Notice how the form fields are appended to the URL as query parameters.

We can also use the post method like this:

<form action="/greetings" method="post">
<input name="say" value="Hi">
<input name="to" value="Mom">
<button>Send my greetings</button>
</form>

And it will create this HTTP request:

POST /greetings HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
say=Hi&to=Mom

Notice how the form fields are sent in the body of the request.

The method our forms use impact on how we extract the form fields from the request on the server-sidetitle:

If we use get, we can extract the values using req.query like this:

router.get('/greetings', function (req, res) {
const greeting = req.query.say
const recipient = req.query.to
// ...
})

If we use post, we must parse the body of the request. To do this, we need an additional module:

import express from 'express'
const server = express()
server.use(express.urlencoded())
router.post('/greetings', function (req, res) {
const greeting = req.body.say
const recipient = req.body.to
// ...
})

server.use(express.urlencoded()) is Node.js middleware that parses the body of requests and places the parameters as properties on req.body.

Resources