Chapter 11: Transactions on the Web

11.3 Forms and Databases

Forms are a way to send user input to a server, which must then process that information and send a response as a new Web page. Express makes this easy by letting you define routers that handle form input.

Forms in HTML
Processing Forms
Interacting with Databases

Forms in HTML

In Chapter 9 we learned about various types of user input such as buttons, text fields, etc. We used JavaScript to process those actions locally, but in many cases you’ll want to let your Web server process those actions and send back a response.

As an example, let’s wrap a text input field in a form within the document index.ejs, which will change the title of the default Web page:

<p>
    <form action="/" method="POST">
        <label>
            <span class="label">Change this page’s title:</span>
            <input type="text" id="title" name="title" value="" placeholder="<%= title %>" />
            <input type="submit" />
        </label>
    </form>
</p>

Express

Welcome to Express

The attribute action provides the path to the script on the server that will process these requests. In this case, we’ll use the same document that the server sent to the browser in the first place, which is at the origin of the Web site, /.

Notice that the attribute name must now appear in this <input type="text"> element, unlike the previous example where it wasn’t necessary. This allows a name-value pairing like radio buttons and menus have. In this case that would be:

title: "Express"

which is the original value established by the server, or whatever other text the user provides in the input field.

When the user types in a new value, e.g. Geography of New England, and clicks the Submit button, the browser sends the form’s name-value pairs back to the server using the HTTP method POST. This is very similar to the GET method, but sends the information as the body of the request instead of being appended as part of the URL (like HTTP responses, HTTP requests also have headers). It is understood as providing information to rather than requesting information from the server.

Processing Forms

To process the content from a form, a Web server needs to run a designated program, which is accessed via a Common Gateway Interface (CGI). Such programs are therefore known as CGI programs or CGI scripts. They can be written in just about any programming language, but the most common nowadays are Java, PHP, and Perl, though Ruby, Python, and JavaScript are becoming quite popular.

Because Node is first and foremost a JavaScript environment, its CGIs don’t require a special “interface”, they are simply loaded like other JavaScript code. You also don’t need to learn another programming language!

In Express’ default set up, any request from a browser is passed through several filters. The key-value pairs in a POST request are extracted by the body-parser module that was implemented when app.js was initially run:

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));

(Without a path as its first argument, app.use filters are applied to all paths.)

The processed request is placed into a request object that can be referenced for its values, in particular by the callback function of the router:

/* POST to home page. */
router.post('/', function(request, response, next) {
    if (request.body.title)
        title = request.body.title;
    else
        title = 'Express';
    response.render('index', { title: request.body.title });
});

If the user types something else into the text field, e.g. Geography of New England, that value is sent back to the server and processed into the property request.body.title, and the response page includes that new value:

Geography of New England

Welcome to Geography of New England

Interacting with Databases

Databases do not in general have their own Web interface, and so can’t be queried directly by Web browsers. But Web servers can communicate with them to make queries and insert new values and update them on behalf of users. Node is no exception, but you’ll need to install another package!

You can access Postgres from Node by adding the PG package. First change directory into the Web site folder, e.g.

cd gnex

Then type the command

npm install pg --save

The option --save will add PG to the file package.json so that it will automatically be included in future updates.

To make PG available to a particular router, include the statement

pg = require('pg')

in its code. You can then establish a connection to the database and run a query of some sort:

var connection = "postgres://appAccount:appPassword@localhost/database";
pg.connect(connection, function(err, client, done) {
    client.query('INSERT INTO pagenames (name) VALUES ($1)', title);
    done();
})

Here the positional parameter $1 will be replaced by the value of title.

You can find a more complete example here. Note the use of error handling. Remember, these are run asynchronously!

results matching ""

    No results matching ""