How to setup a Node.js server with Express in less than 5 minutes

Today I wanted to create a mock server to serve json to my app before creating the full fledged backend in php which will ultimately serve me the real API. I chose to do it with node.js, express and heroku as it allows you to set up the whole thing up in a very short time and with as little hassle as possible.

To get started, you need to install on your mac heroku, node.js and npm (a nodejs package manager).

Installing Heroku on Mac

Heroku_logo.svg

Heroku (pronounced her-OH-koo) is a cloud application platform where you can deploy web apps for free with just a few commands from the terminal. To use it, you must create an account, it’s quick and it’s free as long as you don’t have a big traffic. The great advantage is that it allows you to scale very easily if you app takes off, and to pay only for whatever traffic/cpu you use.

To install heroku on your mac, you can run brew install heroku-toolbelt , or download their mac installer via the Heroku Toolbelt website.

Installing Node.js and NPM

nodejs-logo

To install node.js and npm, run brew install node , or download the installer from Node.js website.

Setting up the node.js server locally and on Heroku

Once you have everything, create a new directory, navigate to it through command line and run the following commands successively:

#Create the app locally
npm init #initialize npm
npm install —save express #install express and add it to the package manager json file
sudo  npm install express-generator -g #create the app
express -> y -> express —git #add gitignore

#Setup heroku
heroku login #login with your heroku login credentials
heroku create #create the app on heroku
heroku apps:rename name-of-my-app

#Initialize git repository
git add .
git commit # press `i` to insert a comment, write your comment, press `esc` and then `:x` to save
git push heroku master #push your app to heroku

#Open a new tab in your browser to see your heroku app server
heroku open

With the last command your browser should open a basic html page with a title saying “Welcome to Express”. Your server is up and running on the cloud, but to be honest it’s a bit of a hassle to have to stage, commit, and push everytime you make a change. As long as you are developing you can test your code on your local server by running heroku local or npm start .

However, everytime you change your code you will have to stop the server (ctrl+c), and restart it with the same command. A great tool to ease the process is `nodemon`. You can install it via sudo npm install -g nodemon , and run it with the command nodemon . Nodemon will then monitor your changes and restart the server whenever you save something, which allows you to just refresh the page in your browser (which should be accessible through http://localhost:3000/) to see your latest version!

Sending and receiving basic json with your Node Server

Now if you go in your project directory you will see a brand new node.js app installation. Here is a breakdown of its content:

  • /bin : contains the http server, equivalent to apache, open routes, answer to socket requests, and calling app.js (createserver(app.js), which contains setup the app and import the required modules
  • /public : contains all the static files (img, javascript, stylesheets etc)
  • /routes : contains the routes where all the code logic is going to sit
  • /views : contains the jade templates for each html page

To do a basic routing system, we are going to create a file name called `api.js` in the /routes folder. We need to include it in `app.js` so the app know that it needs to load this file, you can do so by adding the following lines :

#under var = routes ..
var api = require('./routes/api');

#under app.use('/', routes);
app.use('/api', api);

Now in app.js we are going to create the get and post requests. Open it, and paste the following example into it:

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

//Get all accounts
router.get('/accounts', function(req, res, next) {

    var accounts = require('./data/INAccount');
    var vehicles = require('./data/INVehicle');
    accounts.forEach(function(val,key,arr){
      arr[key].vehicles = vehicles;
    });
    console.log(accounts);
    res.json(accounts);

});

//Get account by id
router.get('/account/id/:id', function(req, res, next) {

  console.log(req.params.id);
  if(typeof req.params.id == 'undefined' ){
    res.json({success:false});
  }
  else {
    var accounts = require('./data/Account');
    var account = null
    accounts.forEach(function(val,key,arr){
      if (req.params.id == arr[key].id) {
        account = arr[key];
      }
    });
    console.log(account);
    res.json(account);
  }

});

//Post Document: post localfilename, type | return : remote url
router.post('/document/', function(req, res, next) {
  if(typeof req.body.localfilename == 'undefined' || typeof req.body.type == 'undefined'){
    res.json({success:false});
  }
  else {
    var data = {"remoteUrl":"https://upload.wikimedia.org/wikipedia/commons/f/f2/Vehicle_Insurance_Certificate_in_India.pdf"};
    res.json(data);
  }

});

As the json file can be a bit big, we put them in a separate folder. In /routes, create a /data folder, and create `Account.json` file. In it, paste some json to return to your app:

[
  { "id": 1,
    "name":"Alan",
    "email":"[email protected]",
  },
  { "id": 2,
    "name":"Mary",
    "email":"[email protected]",
  },
  { "id": 3,
    "name":"Kate",
    "email":"[email protected]",
  },
  { "id": 4,
    "name":"Eva",
    "email":"[email protected]",
  }
]

That’s it! Now if you go to `http://your-heroku-app.herokuapp.com/api/accounts`, you should see the account data displayed in the browser. You can also try out the post request with Postman, or any other post request plugins.

And as usual let me know if something is unclear, I’ll be happy to help you out!