Playing with Express()

For the first week, our goal was to play around with Express to get a feel for it.  I’ve used express to build my personal website, so I decided to focus some time on an aspect I hadn’t spent much time diving into.  Specifically POST requests and utilizing Node to write to the filesystem.  Basically it serves as a way to store data locally on the server, rather than use a service like MongoDB.  It’s great for testing with small amounts of data.  Sure, if I’m ever doing larger scale work it would make sense to upgrade to a service that gives me lots more space, but for small scale testing writing to the filesystem is great for quick and dirty tests.  It was also a quick way to play around with Handlebars to get a feel for how to dynamically write from a database into a template and render the data as it comes in.

I used the express generator to build a new project template and went from there.  The first step was to build a simple form.  I wasn’t focused on styling otherwise I might throw some css in here, but this is just to play with raw functionality:

<form action='/form-submit' method='post'>
    <label for='name'>Name</label>
    <input type='text' id='name' name='name' placeholder='Name' />
    <label for='favoriteColor'>Favorite Color</label>
    <input type='text' id='colorInput' name='favoriteColor' placeholder="What's your favorite color?" />
    <button type='submit'>Log your favorite color</button>
</form>

The only noteworthy stuff here is that form automatically submits and HTTP POST request when a button with type=’submit’ is tapped.  It really makes this kind of request dirt simple, which is nice.  Handling it on the server side ended up looking like this:

// Handle a post request with designated url
router.post('/form-submit', function(req, res, next) {
    // Get data sent from form element    
    var obj = {
        name: req.body.name,
        color: req.body.favoriteColor
    };
    // Push submitted data into our data.json file
    database.push(obj);
    // Object must be 'stringified' so that we write proper JSON syntax to the file
    var jsonData = JSON.stringify(database);
    // Write new data to local file    
    fs.writeFile('data.json', jsonData);
    // Render the same page, but with an added parameter to be rendered
    res.render('home', {people: database});
});

It took me a bit of searching to figure out where the form elements existed on the req object. Eventually I found that they live on body. Writing to the file system also took some trial and error, where I initially was not calling JSON.stringify, and simply writing the raw object to the data file. It half worked, but because it wasn’t writing actual JSON sytnax, everytime I would restart the server it would crash because node was trying to read an invalid json file.

Writing to the file system requires a standard node module called fs, and I also had to declare the database file.  So at the top of my app.js file I included the following lines:

var database = require('../data.json');
var fs = require('fs');

Node is smart enough to know that if you load a json file, that it should parse it and translate it into an object.  Pretty neat.

Lastly, came writing the contents of the database file to the browser window.  Above we rendered the home page again, and passed in the database array to the handlebars file.  So in home.handlebars all we have to do is loop through the array and print out the contents like so:

{{#if people}}
    {{#each people}}
      <p> {{name}} : {{color}} </p>
    {{/each}}
{{/if}}

Each item in the people array is an object with properties ‘name’ and ‘color’. Handlebars can grab these directly while iterating through an array using {{#each}}. And that’s all for now. More interesting stuff to come as we move forward. This was just re-familiarizing myself with Express as a framework and now I’m ready to dive into some meatier stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *