Posts Tagged ‘happypolack’

Building a simple joke site with nodejs – Part 4 – Adding our joke routes

Wednesday, July 15th, 2015 by Phillip Napieralski

Last time, we got a basic expressjs app setup. Now, let’s bring in the stuff we created from part 2 and add to it in an expressjs way. This is the first step to awesomeness!

Adding our flat file “database” into the mix

Let’s start by building off the same app that we created in Part 3 – the happypolack auto-generated app.

Remember our JokesDB.json file from part 2? Let’s add that to the happypolack app that we created, but let’s put it in a new folder called model. Go ahead and create that folder and put the jokes json file in there:

		'category': 'chucknorris',
		'content': 'chuck norris joke'
		'category': 'yomomma',
		'content': 'momma joke'

Setting up our /jokes REST endpoints

Let’s create a new route that simply returns a simple “hello world” for our /jokes endpoints. Create the file /routes/jokes.js and add the following code:

// PART 4

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send('GET for /jokes');
});'/', function(req, res, next) {
  res.send('POST for /jokes');

module.exports = router;

All we’re doing with this module is setting up a simple GET path and a POST path. The POST path will “eventually” be used to add a new joke to our database – where as GET path will show a listing of the jokes when your browser goes to that route.

Now, let’s make it so that going to http://localhost:3000/jokes points to this module.

To do this, let’s modify app.js (our default nodejs file). In app.js, add the following code to the top of the file:

var jokes = require('./routes/jokes');

Now, we’ve imported the jokes module. Let’s point /jokes to this module by adding the following code below the line app.use(‘/users’, users) in app.js:

app.use('/jokes', jokes);

That’s it! Now run `npm start` in the console, navigate to http://localhost:3000/jokes and you’ll see our new joke modules simple response ‘GET for /jokes’. Note, we don’t need to test the POST endpoint just yet.

Having our REST /jokes endpoint return the jokes

Bring in the file from Part 2 called database.js. Let’s put this in a new folder called /lib. This is where we’ll put all of our “helper modules”

Here’s our new database.js file so it correctly points to our jokesDB.json flat file database:

var fs = require('fs');

module.exports =
	getJokesFromDB: function()
		return fs.readFileSync('./model/jokesDB.json').toString();

With that in place, let’s modify our /jokes GET endpoint to use this module and output the jokes. Add the following line to the top of your jokes.js file to include that database module:

var db = require('../lib/database.js'); 

Then, change the router.get function to be the following:

router.get('/', function(req, res, next) {
  var jokesJson = db.getJokesFromDB();

Now CTRL+C your currently running node app and re-run `npm start`. Then, navigating to http://localhost:3000/jokes should return you the list of jokes.


That’s it! We’ve got a good start by adding our REST endpoints set-up. We’ll continue to refine the database with CRUD operations and by using MongoDB and (eventually) add in angularjs to the front-end to show the jokes on the index page in a responsive manner!

Building a simple joke site with nodejs – Part 3 – Expressjs

Thursday, June 25th, 2015 by Phillip Napieralski

A simple index-only page won’t do for a joke website. You’ll want to be able to navigate to pages that only have chuck norris jokes, or only have yo momma jokes. Or, perhaps you’ll add a page where users can submit jokes – then of course you’ll need a profile page for users. Let’s use expressjs to get our multiple pages set-up!

Auto-generating a beginning expressjs template

Let’s install express’ project generator tool, but let’s install this globally for the operating system using the -g option:

npm install express-generator -g

Let’s generate a new app called happypolack. For our template engine, we’ll use ejs. We’ll get into this more later.

express --ejs happypolack

Directories overview

Now, if you cd into the happypolack directory, you’ll see a number of different directories. There’s /public, /routes, /views and /bin. The Public directory contains everything that will actually be downloaded by your customers, such as the javascript, images and stylsheets, except for your .HTML code. Your HTML code will go into the /views folder. Though these have a .ejs extension, know that they are essentially HTML with the addition of being able to access server side code through template tags (<%= and %>). See an example of how the title is set using these template tags in /views/index.ejs.

Index, where art thou?

But, where does the title between the template tags come from? It comes from the /routes/index.js file! Let’s take a look at this code in routes/index.js:

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });

Remember in our first tutorials how you had to do “writeHead” and call “responses.end” to actually send data to the user? The way you do this in express is much different.

Let’s say, simply, that you want the web URL to show your index.ejs HTML file, and that’s it. Well, you’ll setup a route (this is index.js) and have that route included in our main app.js file (we’ll get to that). All the code in index.js is doing is setting things up so that when an HTTP GET request goes to the root of our website, it will show/render the “index[.ejs]” file and pass the variable data title.

Now, open up app.js that was generated in the root directory for you. This file is essentially our main. The top 24 lines are simple set-up that you don’t need to worry about immediately. However, let’s look at these lines of code:

var routes = require('./routes/index');
var app = express();
app.use('/', routes);

Understand this already? That route that was generated for us (routes/index.js) was simply a node module. This node module will be loaded whenever the base URL (‘/’) is navigated to by your customer (in my case I want it to be Let’s see this in action!

Lights, camera, action!

First, express included a bunch of dependencies in a package.json file. A package.json file is the main identifier for a node module. Inside of that file, there’s is an array of “dependencies” that your module requires. To install all of those dependencies, it’s easy! Type the following:

npm install

You’ll now see a bunch of new directories/modules inside a folder called node_modules.

Now run your app using either node app.js or, easier, the npm command:

npm start

By default expressjs generated apps use port 3000. Now navigate your browser to:


You should see a basic “Welcome to Express” web page. That’s it!


You’ve seen how to setup expressjs and now you should have a basic understanding of the structure expressjs creates for you. Next time, we’ll add back our basic flat file “database” and start showing some jokes!

See the rest of this tutorial series

Part 1 – Hello World
Part 2 – Adding our flat file “database”