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

.NET Core 2.0 Changes – 4 Key Things to Know

1. .NET Standard 2.0 Expanded APIs & the Ability to Reference Full Framework Libraries .NET Standard broadens the set of APIs available to include a lot of the missing features. It now supports 32,000+ APIs. It is now much easier to port your code to a .NET Standard library without major code changes. One of the biggest problems with .NET Core was the lack of third-party libraries. For example, when 1.0 came out, popular logging libraries like log4net were not even available (it is now). However, this was really only a problem if you wanted to deploy your app on Mac or Linux. You could have used .NET Core and targeted full .NET framework and not had these issues. .NET Standard 2.0 has added a  new compatibility shim  that will enable any .NET Core app to reference any full framework library. 2. Expanded OS Support One of the big goals with .NET Core is portability across multiple operating systems. Including desktops, servers, and even mobile. Microsoft ...

ASP.NET Core - MVC Design Pattern

The MVC (Model-View-Controller) design pattern is a design pattern that's actually been around for a few decades, and it's been used across many different technologies, everything from Smalltalk to C++ to Java and now in C# and .NET as a design pattern to use when you're building a user interface. The MVC design pattern is a popular design pattern for the user interface layer of a software application. In larger applications, you typically combine a model-view-controller UI layer with other design patterns in the application, like data access patterns and messaging patterns. These will all go together to build the full application stack. The MVC separates the user interface (UI) of an application into the following three parts − The Model  − A set of classes that describes the data you are working with as well as the business logic. The View  − Defines how the application’s UI will be displayed. It is a pure HTML which decides how the UI is going to loo...

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. ...