Skip to main content

Setting Up Our Node Application server.js

Since this is our starter kit for a single page MEAN application, we are going to keep this simple. The entire code for the file is here and it is commented for help understanding.
// server.js

// modules =================================================
var express        = require('express');
var app            = express();
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');

// configuration ===========================================
    
// config files
var db = require('./config/db');

// set our port
var port = process.env.PORT || 8080; 

// connect to our mongoDB database 
// (uncomment after you enter in your own credentials in config/db.js)
// mongoose.connect(db.url); 

// get all data/stuff of the body (POST) parameters
// parse application/json 
app.use(bodyParser.json()); 

// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true })); 

// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override')); 

// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public')); 

// routes ==================================================
require('./app/routes')(app); // configure our routes

// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);               

// shoutout to the user                     
console.log('Magic happens on port ' + port);

// expose app           
exports = module.exports = app;                         


We have now pulled in our modules, configured our application for things like database, some express settings, routes, and then started our server. Notice how we didn’t pull in mongoose here. There’s no need for it yet. We will be using it in our model that we will define soon.
Let’s look at config, a quick model, and routes since we haven’t created those yet. Those will be the last things that the backend side of our application needs.

CONFIG CONFIG/

I know it doesn’t seem like much now since we only are putting the db.jsconfig file here, but this was more for demonstration purposes. In the future, you may want to add more config files and call them in server.js so this is how we will do it.
// config/db.js
    module.exports = {
        url : 'mongodb://localhost/stencil-dev'
    }

Now that this file is defined and we’ve called it in our server.js using var db = require('./config/db');, you can call any items inside of it using db.url.
For getting this to work, you’ll want a local MongoDB database installed or you can just grab a quick one off services like Modulus or Mongolab. Just go ahead and create an account at one of those, create a database with your own credentials, and you’ll be able to get the URL string to use in your own config file.
Next up, we’ll create a quick Mongoose model so that we can define our Nerds in our database.

NERD MODEL APP/MODELS/NERD.JS

This will be all that is required to create records in our database. Once we define our Mongoose model, it will let us handle creating, reading, updating, and deleting our nerds.
Let’s go into the app/models/nerd.js file and add the following:
// app/models/nerd.js
// grab the mongoose module
var mongoose = require('mongoose');

// define our nerd model
// module.exports allows us to pass this to other files when it is called
module.exports = mongoose.model('Nerd', {
    name : {type : String, default: ''}
});
This is where we will use the Mongoose module and be able to define our Nerd model with a name attribute with data type String. If you want more fields, feel free to add them here. Read up on the Mongoose docs to see all the things you can define.
Let’s move onto the routes and use the model we just created.

NODE ROUTES APP/ROUTES.JS

In the future, you can use the app folder to add more models, controllers, routes, and anything backend (Node) specific to your app.
Let’s get to our routes. When creating a single page application, you will usually want to separate the functions of the backend application and the frontend application as much as possible.

Separation of Routes

To separate the duties of the separate parts of our application, we will be able to define as many routes as we want for our Node backend. This could include API routes or any other routes of that nature.
We won’t be diving into those since we’re not really handling creating an API or doing CRUD in this tutorial, but just know that this is where you’d handle those routes.
We’ve commented out the place to put those routes here.
 // app/routes.js

// grab the nerd model we just created
var Nerd = require('./models/nerd');

    module.exports = function(app) {

        // server routes ===========================================================
        // handle things like api calls
        // authentication routes

        // sample api route
        app.get('/api/nerds', function(req, res) {
            // use mongoose to get all nerds in the database
            Nerd.find(function(err, nerds) {

                // if there is an error retrieving, send the error. 
                                // nothing after res.send(err) will execute
                if (err)
                    res.send(err);

                res.json(nerds); // return all nerds in JSON format
            });
        });

        // route to handle creating goes here (app.post)
        // route to handle delete goes here (app.delete)

        // frontend routes =========================================================
        // route to handle all angular requests
        app.get('*', function(req, res) {
            res.sendfile('./public/views/index.html'); // load our public/index.html file
        });

    };


This is where you can handle your API routes. For all other routes (*), we will send the user to our frontend application where Angular can handle routing them from there.

BACKEND DONE!

Now that we have everything we need for our server to get setup! At this point we can start our server, **send a user the Angular app (index.html), and handle 1 API route to get all the nerds.
Let’s create that index.html file so that we can test out our server.

CREATE AN INDEX VIEW FILE PUBLIC/VIEWS/INDEX.HTML

Let’s just open up this file and add some quick text so we can test our server.
 <!-- public/views/index.html -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <title>Starter MEAN Single Page Application</title>

</head>
<body>

    we did it!

</body>
</html>

Comments

  1. It is useful, can you please add more angular stuff?

    ReplyDelete

Post a Comment

Popular posts from this blog

Scenario : Cloud Computing

ASP.NET Core - MVC Setup

Here we will set up the MVC framework in our FirstAppDemo application. We will proceed by building a web application on top of the ASP.NET Core, and more specifically, the ASP.NET Core MVC framework. We can technically build an entire application using only middleware, but ASP.NET Core MVC gives us the features that we can use to easily create HTML pages and HTTP-based APIs. To setup MVC framework in our empty project, follow these steps − Install the  Microsoft.AspNet.Mvc  package, which gives us access to the assemblies and classes provided by the framework. Once the package is installed, we need to register all of the services that ASP.NET MVC requires at runtime. We will do this inside the  ConfigureServices  method. Finally, we need to add middleware for ASP.NET MVC to receive requests. Essentially this piece of middleware takes an HTTP request and tries to direct that request to a C# class that we will write. Step 1  − Let us go to the NuGet package manager by ri

SQL Server Tutorial - Date functions

1. Get month names with month numbers: In this query we will learn about  How to get all month names with month number in SQL Server . I have used this query to bind my dropdownlist with month name and month number. 1 2 3 4 5 6 7 8 9 10 11 12 ;WITH months(MonthNumber) AS (      SELECT 0      UNION ALL      SELECT MonthNumber+1      FROM months      WHERE MonthNumber < 12 ) SELECT DATENAME(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) AS [MonthName],Datepart(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) AS MonthNumber FROM months ORDER BY Datepart(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) ; 2. Get name of current month: In this query we will learn about  How to get name of current month in SQL Server . 1 select DATENAME(MONTH, GETDATE()) AS CurrentMonth 3. Get name of day: In this query we will learn about  How to get name of day in SQL Server . 1 select DATENAME(WEEKDAY, GETDATE()) AS TodayI