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.
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.
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()
.
Part of Databases
- Introducing databases
- Organising a databaseP
- Using a database driverP
- Creating modelsP
- Making forms workP
- Collecting form dataP
- Saving form dataP