BETAThis is a new service – your feedback will help us to improve it.

Collecting form data

Now our form is prepared, the next step is to modify our server to collect the data and save it to the database.

When we submit a form, our browser makes a request to a URL. The data in the form is contained inside that request.

We can tell the form where to make the request to by adding some attributes to the <form> tag:

<form action="/comment/new" method="post">
  <!-- Form inputs go in here -->
</form>

The action attribute is the URL the form will send its data to.

Make sure each form in your app submits to a sensible URL.

Routing

We need to create a route in our server.js file that will handle requests made to that URL.

We could create a route like this:

server.post("/comment/new", function(req, res){
  console.log(req.body)
  res.render('index.njk')
})

This route looks a little different to the others.

It starts with server.post(), rather than server.get().

When our browser requests a webpage, it is normally making a get request (getting data from the server), so we use server.get() to handle that request.

When forms are submitted, the browser makes a post request (sending data to the server), so we have to use server.post().

Secondly, we log something called req.body to the terminal. req is actually short for request. req.body is how we access the data submitted from the form.

Finally, res.render('index.njk') will respond to the request with the index view.

You have to decide which view makes sense to present to a user once their form has been submitted. If your form adds a new entry to a list, it often makes sense to send a user straight back to that list.

Create a route to handle submissions from each form in your app.

Reading form data

We need to install and set up body-parser, an extra piece of software that will read the data that comes in a request.

Without it, we won't be able to see the data coming in from form submissions.

From the /my-app folder, run the following terminal command:

npm install --save body-parser

Then the following line to the top of your server.js file:

const bodyParser = require('body-parser');

And add the following lines just above your first route:

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));

// Your routes down here
// ...

You should now be able to test your form out. Restart your app, go to the page with the form, and make submit it with some data.

You should see the data you submitted appear in the Codenvy terminal, and your browser should show the view you named in res.render().

Make sure that you can successfully collect data from your users using HTML forms and routes.
Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Databases
  1. Introducing databases
  2. Organising a databaseP
  3. Using a database driverP
  4. Creating modelsP
  5. Making forms workP
  6. Collecting form dataP
  7. Saving form dataP