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

ASP.NET Core - Create New Project

You can start building a new ASP.NET Core Application from the  File → New Project  menu option. On the New Project dialog box, you will see the following three different templates for Web projects − ASP.NET Web Application  − The simple ASP.NET application templates . ASP.NET Core Web Application (.NET Core)  − This will start you with a crossplatform compatible project that runs on the .NET Core framework. ASP.NET Core Web Application (.NET Framework)  − This starts a new project that runs on the standard .NET Framework on Windows. In the left pane, select  Templates → Visual C# → Web  and in the middle pane select the ASP.NET Core Web Application (.NET Core) template. Let us call this application  FirstAppDemo  and also specify the Location for your ASP.NET Core project and then Click OK. In the above dialog box, you can select a specific template for the ASP.NET application from the available ASP.NET Core Templates. ...

Become a MEAN Stack Developer

The MEAN stack is  MongoDB ,  Express.js ,  AngularJS  (or  Angular ), and  Node.js . Because all components of the MEAN stack support programs written in JavaScript, MEAN applications can be written in one language for both  server-side  and  client-side  execution environments. MEAN  was coined by Valeri Karpov, a MongoDB developer. He introduced the term in a blog post. The logo concept, initially created by Austin Anderson for the original MEAN stack  LinkedIn  group, is an assembly of the first letter of each component of the MEAN acronym. The components of the MEAN stack are as follows: M ongoDB, a NoSQL database E xpress.js, a web application framework that runs on Node.js A ngular.js or  A ngular, JavaScript MVC frameworks that run in browser JavaScript engines N ode.js, an execution environment for event-driven server-side and networking appl...