In this series of blog posts, we’re looking at how to set up a simple web app in node.
In the previous installment we looked at storing data, the node way.
In this post we’ll look at moving code into the browser, to make a single page application - the node way!
Creating an API
Let’s add some extra routes to our express app, to allow data to be posted and retrieved in JSON format. The code is very simliar to the code we had before, so you can replace the existing routes, or add these as well:
(the only real difference is that we’re calling
json on the response object).
We’ll also need to allow json to be posted. Let’s set up the body parser middleware to handle JSON by adding this line (you can add it next to your existing body parser line)
That’s a simple JSON API set up, you should be able to see your todos if you start up the web server and open this page in your browser:
Now let’s focus our effort on the browser.
Let’s create a new directory for the source code which will run in the browser (so it doesn’t get confused with the server-side code).
One of the first things we want to do it connect to our API.
Let’s call this
http-request.js and put it in the
Next let’s create an
index.js file which we’ll use to call this module.
Hold on! This looks like node.js code. We’re using the
require function to load our
http-request module, which we’re loading off the disk.
require isn’t available in the browser (and neither is the
module.exports variable!), so what’s going on?
require to figure out which files we’re using, it then bundles all of the referenced modules together into a single file.
Browserify has some fantastic benefits:
- We can split our client-side code into small, testable and reusable modules.
- We don’t have to worry about polluting the global namespace. All variables will be encapsulated within their own module.
- We can tap into the npm registry, and use node.js modules in the browser.
Put another way, browserify brings the benefits of node to the browser.
-goption installs the module globally, and registers it as a command line tool.
Now we can create the bundle on the command line:
This command will create an
index.min.js file in the
There are lots of automation tools in node, grunt and gulp being popular options. I normally create a makefile - but perhaps I’m old fashioned :¬)
Now let’s create an
index.html in the
public directory which will load the script file:
Note that I have abandoned the server-side views, this static HTML file will be served instead.
If you fire up the application, you should now see your todos written to the console (open the developer tools with
Next we’ll look at using React for templating in the browser.