Consuming Express (NodeJS) REST API with Jade

By | 02/07/2015

In this post, we created a REST API server that allows a client to add, update, delete and show todo items. One could use a REST client, such as POSTMAN, to consume the REST API services exposed by the REST server developed in Express (NodeJS).

In this post, we are going to clone the repository from Github and modify it to include some user interfaces by using the Jade template which comes as part of the Express framework. Let’s get started….

wim@ubuntu:~/Blog$ git clone https://github.com/wiwa1978/blog-express-todo-mongo-api.git Express_Todo_Mongo_API_Jade

The github repository is now cloned in a folder called ‘Express_Todo_Mongo_API_Jade’. To ensure everything is OK, let’s try to run the application.

wim@ubuntu:~/Blog/Express_Todo_Mongo_API_Jade$ node bin/www 

Going to http://localhost:3000 will show you the welcome page of the Express generator.

Let’s now start the real work and add some Jade templates to be able to view, create, update and delete todo items. To do so, we will create a subdirectory called ‘todos’ in the ‘views’ directory. As we want a really nice layout, we will first ensure that we can use the Bootstrap framework. To do this, add a reference to the Bootstrap framework in the layout.jade file. The complete content of this file is in below snippet.

doctype html
html
    title Express Todo
    link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css")
body
    block content

Then, in the newly created todos folder, we will create a page called ‘index.jade’. This file will show all todo items currently in our Mongo database.

extends ../layout

block content
  div.container
    h2 Todo Application
    div.content
      table.table
        a.btn.btn-primary( href="/todos/new" ) Add Todo
        thead
          tr
            th Content
            th Description
            th Status
            th Created
            th Updated
            th Actions
        tbody
          - each todo, i in todos  
            tr
              td #{todo.content}
              td #{todo.description}
              #{todo.completed}
              if todo.completed
                td Completed
              else
                td Pending
              td #{todo.created_at)
              td #{todo.updated_at}
              td 
                a.btn.btn-success( href="/todos/#{todo._id}/edit" ) Edit  
                   
                a.btn.btn-info( href="/todos/#{todo._id}/show" ) Show
                   
                form(action='/todos/#{todo._id}/delete',method='post',enctype='application/x-www-form-urlencoded')
                input(type='hidden',value='DELETE',name='_method')
                button.btn.btn-danger(type='submit') Delete
                p 

In the above snippet, you can see that we fill a Bootstrap table by looping over all todo-items using a for each loop. For each todo item, we print the ‘content’, ‘description’, ‘completed status’, ‘created_at’ and ‘updated_at’ date. Here and there, we applied some more Bootstrap functionality (cfr the span class to indicate a ‘completed’ or ‘pending’ state). You can view the output by going to http://localhost:3000/todos.

It looks as follows:

Todo_Index

You’ll see that the ‘created_at’ and ‘updated_at’ dates are looking ugly. We will use moment.js to format them to an appropriate format.

wim@ubuntu:~/Blog/Express_Todo_Mongo_API_Jade$ sudo npm install moment --save
moment@2.10.3 node_modules/moment

Then we need to ensure that our Express app knows about the momentjs library.

var moment = require('moment');
app.locals.moment = require('moment');

Once this is done, we can use the momentjs functionality to give the dates a more usable format. To do this, replace the following code in ‘todos/index.js’

  td #{todo.created_at}
  td #{todo.updated_at}

by this code:

td #{moment(todo.created_at).format('DD/MM/YYYY -- HH:mm:ss')}
td #{moment(todo.updated_at).format('DD/MM/YYYY -- HH:mm:ss')}

The final result now looks like:

Momentjs

Let’s now continue to add some more functionality, e.g add todo items to the Mongo database:

extends ../layout
block content
  div.container
    h2 Add Todo item

    div.content
    form#formAddTodo(name="addtodo",method="post",action="/todos")
        p
            input#content.form-control(type='content', name='content', placeholder='Content')
        p
            input#description.form-control(type='description', name='description', placeholder='Description')
        p
            .checkbox
                label
                    input(type='checkbox', name='completed')
                    |  Completed
        p
            button.btn.btn-primary(type="submit") Add Todo

Easy enough…you add a form, provide the text input fields for the content, the description and a checkbox for the completed item and a button that effectively adds the item to the Mongo database. Looking behind the curtains, you will hit the server with an HTTP POST to http://localhost:3000/todos.

I refer to the Github repository to see the Jade files for the update and delete functionality.

We will now test the webapplication a little bit using POSTMAN and the web interface:
We will start with an empty todo list as shown in the following screenshot:

1.EmptyTodoList

Then we will add a single Todo item using the webinterface:

2.AddItem

Using the webinterface, we ensure that the item has been properly added to the Mongo database:

3.OverviewAllItems

Obviously, also using POSTMAN will give us the same Todo item:

4.Postman_AllItems

Then, let’s try to update the todo item:

5.UpdateBox

Again, we verify using the webapplication if it was updated successfully:

6.Updated_AllItems

This is obviously also reflected in POSTMAN:

8.Postman_AllItemsAfterUpdate

Deleting a todo item using the webapplication also works. To verify the deletion was successful, you could do again a POSTMAN query as indicated in the below screenshot:

9.Postman_afterDelete

Please refer to the Github repository for the full source code.

Have fun!!