{ Collecting Form Data with Express. }

Objectives:

By the end of this chapter, you should be able to:

  • Compare and contrast GET and POST requests
  • Collect form data from a GET request using req.query
  • Collect form data from a POST request using req.body
  • Diagram how a redirect works and what the location header is

Data from a GET request

One of the most important things to understand when building server-side applications is how to send data in the request and how to respond based on what the request data contains. One of the most common ways of sending data to a server is through an HTML form.

Let's see what this looks like when we use pug to generate a form and express to access user input from that form. Imagine we have a template called new-user.pug and inside this is what it contains:

form(action="/create-new-user")
    input(type="text" name="first")
    input(type="text" name="last")
    input(type="submit" value="Create a user!")

When this form is submitted, how do we access that data on the server? We first need to create a GET route for /create-new-user. Inside of here we will use a special object called query to examine form values. In order to send data to the server, our inputs must have a name attribute. The value of the name attribute is what will be the key in the query object that we have access to on the server.

Now here is what our app.js might look like:

var express = require("express");
var app = express();

app.set('view engine', 'pug')

app.get('/', function(request, response){
    response.render('new-user')
})

app.get('/create-new-user', function(request,response){
    // let's examine the data from the query string
    // using request.query! We will have two keys of first and last
    // since those are the values of the name attributes from our form
    response.send(request.query)
});

app.listen(3000, function(){
    console.log("The server has started on port 3000. Head to localhost:3000 in the browser and see what's there!")
})

When you submit a form via a GET request, the form data gets added to the query string. Since data is populated in the query string, accessing data from a form when a GET request is made is done through the query object, which itself is attached to the request object.

What about a POST request? In this case, things are a bit different since there is no query string that we can access.

Data from a post request using body-parser

In order to capture values from a form when a POST request is made, we need to get data from the 'body' of the form. Express does not come with any built in tool to do that, so we need to install a package called body-parser, which will add an object called body to the request object. Let's first run npm install --save body-parser in the terminal to make sure we install the module.

var express = require("express");
var app = express();

// include body-parser
var bodyParser = require("body-parser");

// use body-parser
app.use(bodyParser.urlencoded({extended:true}));

app.set('view engine', 'pug')

app.get('/', function(request, response){
    response.render('login')
})

app.post('/create-new-user', function(request,response){
    // since we are using body-parser, we now have access to an object on the request object called "body", which contains all the values in the forms
    response.send(request.body)
});

app.listen(3000, function(){
    console.log("The server has started on port 3000. Head to localhost:3000 in the browser and see what's there!")
})

Here is what our login.pug view might look like:

form(action="/create-new-user" method="POST")
    input(type="text" name="username")
    input(type="password" name="password")
    input(type="submit" value="Create A User")

redirect

Now that we are successfully posting, what do we do inside of the POST request? Usually we reserve the HTTP verb POST for when there is data being sent to the server to add information. Once we have done that, what happens next? It wouldn't make much sense to render a page that says "Created!" or "Updated!", so instead we redirect back to another route. Here is how the redirect process works:

  1. The server responds with a status code of 302 and a header called location. The value of the header is a URL.
  2. The browser then immediately issues a GET request to the value of the location header
  3. The server responds with data from the request.
app.get('/', function(request,response){
    response.render('welcome')
});

app.post('/data', function(request,response){
    console.log("We create/update/delete some data here");
    response.redirect('/'); // respond to the browser with a header called location and a value of '/'. The browser will see the header and immidiately issue a GET request to '/', where our server will respond by rendering the welcome page.
});

Example App

You can see an example of how to gather data from forms here.

When you're ready, move on to Express.js Exercises

Continue