The body-parser package
If you were paying close attention in the previous activity, you may have noticed that the ACTION method of the FORM element was set to /signup-confirmation. And that the METHOD attribute was set to POST.
We can add a route to our app that will 'handle' this form when it is submitted. But before we do, we must install another package, and then add some middleware code that allows our application to read data that is posted in forms.
Run this command in the terminal to install the 'body-parser' package:
npm install body-parser
Before we can use the body-parser package in our code, we must import it. Add this to the IMPORTS section of app.js:
const bodyParser = require('body-parser');
Now add this code to the MIDDLEWARE section in app.js (don't worry about understanding this line of code - just know that it allows our app to collect data submitted in HTML forms):
// allow the app to receive data from form submits
app.use(bodyParser.urlencoded({ extended: true }));
Add this code to the ROUTES sections of app.js:
app.post('/signup-confirmation', (req, res) => {
res.send("Form data received: " + JSON.stringify(req.body));
});
Note that this code is calling the post() method of our Express application object (which is used to receive data from forms).
Also note that because we installed the body-parser packager, the request object (req) will include a property named body, which is an object that contains the data entered into the form. This route simply 'stringifies' the data and then sends it in the response, but in the real-world we would most likely do something else with the data, such as insert it into a database.
Side note about HTTP requests and responses
Now would be a good time to observe the network traffic between the browser and the server. We can observe the
- Open the web developer tools (F12)
- Click on the Network tab
- Submit the signup form in the browser and look at the request and response in the network tab.
- You should be able to find the 'payload' (aka 'body') of the request. This is the data that was entered into the form when the request was sent.
Now let's update the NAV element in top.ejs to look like this:
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/signup">Sign Up</a></li>
</ul>
</nav>
In the next lesson we'll finish the /signup-confirmation route that we started in this lesson.