Introduction

This is a continuation of the MEAN Series, if you feel the need to start from the basics, go ahead and explore the part 1 of the series.

In this part, we will setup the server file and define routes to serve our application on the browser. We will also look at some angularJS concepts and how they work together with nodeJS on the backend to make our life easier.

We’ll be writing our javascript code using ECMAScript 6 (es6), so expect lots of const, let, map and arrow functions. Feel free to check out a resource on es6 if these terms sound strange or you feel your javascript is getting rusty, hopefully you will get some motivation from learning about all the cool stuff we can do using es6. :)

Step 3: Express Server setup and MongoDB connection

Let’s create our app entry point. To do this, we create a server.js file in the project root directory with the following code snippet:

// server.js const express = require('express');

const bodyParser = require('body-parser');

const mongoose = require('mongoose'); const app = express();

const router = express.Router(); // Connect to mongoDB database const mongoURL = 'mongodb:// : @ : / '; mongoose.connect(mongoURL); // Routing // Configure port

const port = 8080; // Listen to port

app.listen(port); console.log(`Server is running on port: ${port}`);

Replace <dbuser>, <dbpassword>, <host>, <port>and <database-name> with your mongodb credentials.

Note:

If you’re using mongodb locally, your host will most likely be localhost and unless you have a username and password set, your connection string may simply just look like:

mongodb://localhost/<dbname>

It automatically creates the database with the name specified in the connection string when you perform an insert query.

If you’re using the online version on mongoDB provided by mlab, you’ll need to log into your account, create a database and a database user, and get the connection string which usually looks like:

We will store the connection string along with other sensitive data in an environment variable in the next tutorial to prevent compromising the security of our application and database. However for this part, we will allow them in the server.js for simplicity, but hey, don’t try this in production. :)

Next thing is to start the application on the terminal using:

node server.js

This will log the following on the terminal if successful:

Server is running on port: 8080

If you see this message, then the server connection to mongodb was successful and our app started successfully. We now proceed to adding some routes and serving some static pages.

Step 4: Server/Backend Routes

In this step, we create the backend route for the application to enable it communicate with our server. To achieve this, we are going to modify our server.js file created earlier and add the following snippet just below Routing:

// server.js . . . // Routing router.get('/', (request, response) => {

response.status(200).send({message: 'Hello World!'})

}); //Set app to use express backend router

app.use(router); . . .

Now we restart our application, open up a browser and navigate to http://localhost:8080/

On your browser window, you should see the message:

{"message":"Hello World!"}

If you see this displayed, our backend route works. awesome!!!

Now we create html files to be rendered on the browser. To do this we run the following unix command from the project root directory:

mkdir public && touch public/index.js && touch public/index.html

This will create a public directory and create index.js and index.html files in it.

Our directory structure should look like:

> node_modules

> public

-- index.html

-- index.js

-- package.json

-- server.js

In the index.js file we add the following snippet:

// index.js angular.module('angularApp', [])

.controller('indexCtrl', function($scope) { // Initialize variables $scope.name1 = ''; this.name2 = ''; $scope.greeting1 = `Hello ${$scope.name1}`; this.greeting2 = `Hi ${this.name2}`;

})

Observe that we are defining two variables that seem to be doing the exact same thing but look slightly different, there has been several opinions on the best way to define variables and methods in an angularjs controller, $scope has been around for sometime, while this just joined the party after angular 1.2. I use both depending on how I’m feeling. Both was also used on angularJS component doc. Which ever one you choose to use, so far I think they both achieve same results. Although whenever you use this, you will have to instantiate the controller as a variable in the view like: ng-controller=”indexCtrl as app” as used below, while if you’re using $scope, you only need ng-controller=”indexCtrl”.

If you feel fascinated by the $scope vs this topic, feel free to research further into it and let me know in the comment section on your findings. For now, we’ll focus on their usage. I will use this for most part of this tutorial because I feel like it :). Actually because I think it reduces the chances of confusing pure text in html as angular variables.

In our index.html file, we add the following snippet:

<!doctype html> <html ng-app="angularApp">

<head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script> <script src="index.js"></script>

</head> <body> <div ng-controller="indexCtrl as app">

<input

type="text"

ng-model="name1"

placeholder="Using $scope variable name"

/>

<br />

<input

type="text"

ng-model="app.name2"

placeholder="Using this variable name"

/>

<br /><br />

<h2 ng-if="name1 != ''"> Hello {{name1}} </h2>

<br />

<h2 ng-if="app.name2 != ''"> Hi {{app.name2}} </h2>

</div> </body>

</html>

Now we update our backend route to render static pages in the public directory. To do this, we add the following snippet to our server.js file just above Routing defined earlier:

// Serve static files app.use(express.static('public'));

We also update our initial backend route to point to /api .

Now our files look like shown below:

server.js:

index.js:

index.html:

Once we have the files above, we go ahead and restart our application and navigate to http://localhost:8080/ on the browser.

We’ll find empty input fields where we can enter text and get hello/hi messages displayed on the browser.

We can also navigate to http://localhost:8080/api and access our app API route.