Form Handling with Express

Dr. Greg Bernstein

Updated March 21st, 2021

Forms & Express

Learning Objectives

  • Use Express.js to handle HTML form requests
  • Understand the difference between ‘GET’ and ‘POST’ type forms
  • Use the appropriate Express.js middleware as needed for form processing

Reference/Code

Get or Post?

<form action="url" method="post or get">

  • get: Form information is encoded into a query string that is appended to the URL when the browser issues the request.

  • post: Form information is encoded into the request body.

get Form Handling

Basic Ingredients

  • Need to serve up an HTML page that contains a form.

    • We’ll use a static page
  • Need to set up Express “route” to handle the form

  • Need to extract parameters from the query string

Form Page

From simpleGetForm.html in the /public directory

<form action="/simple_form_handling" method="get">
    <fieldset>
        <div>
            <label for="name">Name:</label>
            <input type="text" id="name" name="user_name">
        </div>
        <div>
            <label for="mail">E-mail:</label>
            <input type="email" id="mail" name="user_mail">
        </div>
        <div>
            <label for="msg">Message:</label>
            <textarea id="msg" name="user_message"></textarea>
        </div>
        <div><button type="submit">Send your message</button></div>
    </fieldset>
</form>

Express Route Handler

From file simpleGetFormHandler.js:

/*
    Example showing `get` form handling, and static
    file serving.
*/
var express = require('express');
var app = express();
app.use(express.static('public')); // For static assets

// Respond to get request from form page.
app.get('/simple_form_handling', function(req, res) {
    let info = req.query;
    res.send(createHtmlMessage(info));
});



host = '127.0.0.1';
port = '5555';
app.listen(port, host, function () {
    console.log("simpleGetFormHandler.js app listening on IPv4: " + host +
    ":" + port);
});

Function for Response

Templates are normally used but I wanted an Express.js only example

function createHtmlMessage(info) {
    let begining = 
`<!DOCTYPE html>
<html lang="en">
    <head><meta charset="utf-8">
        <title>Get Form Handler Example</title>
        <link rel="stylesheet" href="bottleMessage.css">
    </head><body><div class="message">`,
        end = `</div></body></html>`;
    let content = `<h3>Message for <em>${info.user_name}</em></h3>`;
    content += `<p>${info.user_message}</p>`;
    return begining + content + end;
}

Running It…

Get Form

After Submission…

Get Form Response

Fun Background Patterns

See Websites to Generate SVG Patterns

post Form Handling

References

Basic Ingredients

  • Need to serve up an HTML page that contains a form with post method.

    • We’ll use a static page
  • Need to set up Express “route” to handle the form (post)

  • Need to extract parameters from the request body

Request Body

HTTP request messages can contain a body. These can be formated/encoded in many different ways. We will need help parsing the application/x-www-form-urlencoded content type.

express.urlencoded

  • We’ll use the express.urlencoded method to parse the request body for us.

  • Note that other body parsing middleware is available for Express on NPM.

Form for post

see file public/simplePostForm.html

<form action="/simple_form_handling" method="post">
        <fieldset>
            <div>
                <label for="name">Name:</label>
                <input type="text" id="name" name="user_name">
            </div>
            <div>
                <label for="mail">E-mail:</label>
                <input type="email" id="mail" name="user_mail">
            </div>
            <div>
                <label for="msg">Message:</label>
                <textarea id="msg" name="user_message"></textarea>
            </div>
            <div><button type="submit">Send your message</button></div>
        </fieldset>
    </form>

Form screenshot

Post Form

Express Post Route Handler

File simpleFormHandler.js

const express = require('express');
let app = express();
app.use(express.static('public')); // For static assets
let urlencodedParser = express.urlencoded({extended: true});

// Respond to post request from form page.
app.post('/simple_form_handling', urlencodedParser, function(req, res) {
    console.log(req.body);
    //res.send(req.body);
    res.send(createHtmlMessage(req.body));
});

function createHtmlMessage(info) {
    let begining =
`<!DOCTYPE html>
<html lang="en">
    <head><meta charset="utf-8">
        <title>Put Form Handler Example</title>
        <link rel="stylesheet" href="bottleMessage.css">
    </head><body><div class="message">`,
        end = `</div></body></html>`;
    let content = `<h3>Message for <em>${info.user_name}</em></h3>`;
    content += `<p>${info.user_message}</p>`;
    return begining + content + end;
}

const host = '127.0.0.1';
const port = '5555';
app.listen(port, host, function () {
    console.log("simpleFormHandler.js app listening on IPv4: " + host +
    ":" + port);
});

Routes with multiple callbacks

From Express Router

router.METHOD(path, [callback, ...] callback)

You can provide multiple callbacks, and all are treated equally, and behave just like middleware…

In our case we put the urlencodedParser into the list of callbacks so it will process the body before our callback gets the request.

Response screenshot

Post form response
// reveal.js plugins