Simple Register App using Node, Express, MongoDB and Ajax: Part One.

node

Last week we talked about what Web development/Applications are and gave a guide on setting up the frameworks/tools that we are going to use in this series. If you haven’t yet, you can visit the post here and do the setting up/installing. If you already have them set up, let’s jump straight into things.

Root directory/folder

Start by creating a folder on your desktop, or anywhere else on your machine. This will be your working directory i.e the folder where everything will be stored. Everything you will need for your application will be structured inside this folder. Create the folder and name it registerapp, or any name that tickles your fancy. After doing so open this folder on your Text Editor of choice. I will recommend Atom or Sublime Text. I use Atom.

When you open your root directory on your text editor, it should look something like this:

Screen Shot 2016-05-16 at 10.56.12 AM

 

Getting started.

Open your terminal if you’re using Mac and Git Bash if you’re using Windows. If you do not have Git Bash, do install git from here. I forgot to mention this in the last article but it can be quickly done. You can also read more about git and Github here.

Run the following command to check whether you’ve installed Node:

node -v

It should display the version of node that you’ve installed on your machine.

Navigate to your root folder and create your server file. Name it server.js  Your server file is where you set up your configurations and what Node will look for when you start your application. Node.js is what makes it possible to write applications in JavaScript on the server.

Node works with packages that are used to perform different functions for your application. These packages are sometimes called modules, and can be looked at as bits of reusable code. Packages are a help since they are developed and updated by developers who are focusing entirely on that particular area. You can pull in as many packages as possible in your application, if you need them.

To install these packages we will run a command that looks like this (do not run this at this stage)

npm install

npm comes pre-installed with Node. It means node package manager.

To manage your packages, you’ll need a file called package.json which shows you the modules/packages you have installed. To install this, navigate to your root folder on your terminal/Bash and run:

npm init

You will receive requests asking you about version, description e.t.c. just press Enter until you see the question Is this ok? then press the final Enter to it. Your package.json file has now been created. If you go back to your text editor it should show your server.js file and the package.json file both inside the root folder like this:

Screen Shot 2016-05-16 at 4.39.02 PM

Setting up the Server.

To set up our server, we will need to install a package called Express. Express is a Node.js framework that provides features such as routing and view rendering.

Go back to your bash/terminal, making sure you are in the root folder, run:

npm install express --save

After running this, you will notice a folder named node_modules has been created. Do not delete it. This folder is what contains files for all the packages that you install. You will also notice that your package.json looks like this:

{
  "name": "registerapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.4"
  }
}

Under dependencies, you can see express.

Server file.

We can now write the configurations of our server in our server.js. This is written in ES5 JavaScript. Open your file and add this:

(function() {
  'use strict';
  
})();

The use strict means your code is in strict mode. This should help you catch common coding errors and prevents uncommon actions from taking place.

Require the dependencies/modules/packages that you will use in your application. For now we will need Express.

(function() {
  'use strict';
  // Require dependencies.
  var express = require('express');
})();

Next, define your Express app and the application port number. Port numbers allow different applications on the same computer to utilize resources without conflicting with each other.

(function() {
  'use strict';
  // Require dependencies.
  var express = require('express');

  //Define the Express app
  var app = express();

  //Define the application port
  var port = 2020;
})();

Finally, write the code that starts the server and listens for connections on the defined port:

(function() {
  'use strict';
  // Require dependencies.
  var express = require('express');

  //Define the Express app
  var app = express();

  //Define the application port
  var port = 5050;

  // Start up the server
  app.listen(port, function(err) {
    if (err) {
      console.log('Error connecting to Port');
    } else {
      console.log('Connected on port: ', + port);
    }
  });
})();

The if statement will log out an Error message if there is an error listening to the port. Note: You cannot have two applications running on the same port at the same time.

Now if we run the command:

node server.js

You should see this on your terminal/Bash, if everything went well:

➜  registerapp node server.js
Connected on port:  5050

And when you access this url: http://localhost:5050 on your browser, it will tell you Cannot GET / This is a good sign. It shows that our application is working, but our application does not have a default route. When you type the URL, a request is sent to the server to get the content on the default route ‘/’ to display to the user, but the server does not have anything to respond to that request. This is why you see the error.

Let us now have the server respond with content for the default route. Let us add this just above our app.listen() code:

// Default route
app.get('/', function(req, res) {
  res.send('Hello, we are live!');
});

This tells the server that when a user accesses the application url, it should respond with the words Hello, we are live!

Take note of the two key parameters res and req. These are the HTTP request and response objects. The res object represents the HTTP response that a server sends when it gets a request. The request object contains information regarding the client’s request.

You can kill the server running by pressing CTRL + C and restart it again by running:

node server.js

And when you refresh your page on the browser you should be able to see the words: Hello we are live.

If you have followed this tutorial and everything has worked for you, congratulations let’s meet in the next post. If at one point or the other you got an error while following this, that is very normal. It could be problems with configurations or even a syntax error i.e code not written in correct format. Feel free to tweet us anytime in case you are stuck :)

Link to a sample of what we are building hosted on Heroku : RegisterApp

Link to the code on Github: RegisterApp-CodeBase

You may also like

Leave a Reply

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