Beginning an application from scratch can sometimes be the hardest thing to do. Looking at an empty folder and a file with no code in it yet can be an extremely challenging thing.
In today’s tutorial, we will be looking at the beginning setup for a Node.js, AngularJS, MongoDB, and Express application (otherwise called MEAN). I put those in the incorrect order, I understand.
This will be a beginning point for those that wish to find out how to start a MEAN stack application. Jobs like mean.io and meanjs.org are more totally fledged MEAN applications with many great features you ‘d want for a production project.
You will be able to start from absolute scratch and create a standard application structure that will enable you to develop any sort of application you desire.
This post has been updated to work with Express 4.0
What We’ll Be Structure
A lot of the applications we have actually dealt with so far had a particular function, like our Node and Angular To-Do Single Page Application. We are going to step far from that and just a good old starting application.
This will be extremely barebones but ideally it will help you establish your applications. Let’s just call it a starter package.
- Single Page Application
- Node.js backend with Express and MongoDB
- AngularJS frontend
- Modular Angular elements (controllers, services)
- Good application structure so our app can grow
This tutorial will be more based on application structure and creating a solid foundation for single page MEAN stack applications. For more information on WASTE, authentication, or other subjects in MEAN apps we’ll make sure to write other tutorials to fill those spaces.
The Backend Node, MongoDB, Express
Three letters out of the MEAN stack will be dealt with on the backend, our server. We will develop our server, configure our application, and handle application routing.
Bower isn’t truly necessary. You might pull in all the files we require yourself (bootstrap, angular, angular-route), however bower simply gets them all for you! For more information, read our guide on bower to get a much better understanding.
By the end of this tutorial, we will have a standard application structure that will assist us develop our Node backend along with our Angular frontend. Here’s what it will look like.
We’ll be completing our files into folder structure. All backend work is carried out in server.js, app, and config while all the frontend is handled in the public folder.
Starting Our Node Application package.json
All Node applications will begin with a package.json file so let’s begin with that.
That’s it! Now our application will know that we want to utilize Express and Mongoose.
Note on Express 4 Because Express 4.0, body-parser and method-override are their own modules, which is why we have to include them here. For additional information, here’s our guide to Express 4. Express is a Node.js web application framework that will help us produce our application. Mongoose is a MongoDB ORM that will assist us communicate with our MongoDB database.
Set Up Node Modules
To set up the dependencies we simply setup, just enter into your console and type:
npm install You’ll see your application working to bring in those modules into the node_modules directory site that it develops.
Now that we have those, let’s set up our application in server.js.
Establishing Our Node Application server.js
Since this is our starter set for a single page MEAN application, we are going to keep this basic. The whole code for the file is here and it is commented for assistance understanding.
// server.js// modules ================================================= var express = need(‘reveal’); var app = reveal(); var bodyParser = need(‘body-parser’); var methodOverride = require(‘method-override’);// configuration ===========================================// config files var db = need(‘./ config/db’);// set our port var port = process.env.PORT|| 8080;// link to our mongoDB database// (uncomment after you go into in your own credentials in config/db. js)// mongoose.connect(db.url);// get all data/stuff of the body (POST) specifications// parse application/json app.use(bodyParser.json());// parse application/vnd. api+json as json app.use(bodyParser.json( vnd. api+json’ ));// parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded( ));// override with the X-HTTP-Method-Override header in the demand. mimic 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’));// paths ================================================== need(‘./ app/routes’)(app);// configure our routes// start app ===============================================// start-up our app at http://localhost:8080 app.listen(port);// shoutout to the user console.log(‘Magic occurs on port’ + port);// expose app exports = module.exports = app;
We have now pulled in our modules, configured our application for things like database, some reveal settings, routes, and then began our server. Notice how we didn’t draw in mongoose here. There’s no need for it yet. We will be utilizing it in our model that we will specify quickly.
Let’s look at config, a fast design, and routes given that we haven’t produced those yet. Those will be the last things that the backend side of our application needs.
I understand it doesn’t seem like much now considering that we only are putting the db.js config 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 = localhost
Now that this file is specified and we have actually called it in our server.js using var db = need(‘./ config/db’);, you can call any items inside of it utilizing db.url.
For getting this to work, you’ll desire a regional MongoDB database set up or you can simply get a fast one off services like Modulus or Mongolab. Just proceed and develop an account at one of those, produce a database with your own qualifications, and you’ll be able to get the URL string to utilize in your own config file.
Next up, we’ll produce a fast Mongoose model so that we can specify our Geeks in our database.
Geek Model app/models/nerd. js
This will be all that is needed to create records in our database. As soon as we define our Mongoose model, it will let us manage creating, reading, updating, and deleting our nerds.
Let’s enter into the app/models/nerd. js file and include the following:
// app/models/nerd. js// grab the mongoose module var mongoose = need(‘mongoose’);// define our nerd design// module.exports permits 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 utilize the Mongoose module and be able to specify our Nerd design with a name characteristic with data type String. If you desire more fields, do not hesitate 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 utilize the design we just created.
Node Routes app/routes. js
In the future, you can utilize the app folder to add more models, controllers, routes, and anything backend (Node) particular to your app.
Let’s get to our routes. When producing a single page application, you will normally wish 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 different parts of our application, we will be able to specify as lots of paths as we want for our Node backend. This might include API paths or any other paths of that nature.
We won’t be diving into those considering that we’re not really managing creating an API or doing CRUD in this tutorial, but feel in one’s bones that this is where you ‘d handle those routes.
We have actually commented out the place to put those routes here.
// app/routes. js// grab the geek model we simply developed var Geek = require(‘./ models/nerd’); module.exports = function(app) route to manage all angular demands app.get(‘*’, function(req, res) res.sendfile(‘. );;
This is where you can handle your API paths. For all other paths (*), we will send the user to our frontend application where Angular can manage routing them from there.
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 develop 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 this file and add some fast text so we can check our server.
Test Our Server
With all the backend (and a tiny frontend piece) in place, let’s launch our server. Go into your console and type:
$ node server.js
Now in our console we have:
Now let’s get to the frontend single page AngularJS stuff. The Frontend AngularJS With all of our backend operate in location, we can concentrate on the frontend. Our Node backend will send out any user that visits our application to our index.html file given that we have actually defined that in our catch-all route (app.get(‘*’)).
The frontend work will require a couple of things:
- Files and libraries generated by Bower
- Angular application structure (controllers, services)
- We will produce 3 different pages (House, Nerds, Geeks)
- Manage Angular paths using ngRoute so there are no page refreshes
- Make it quite with Bootstrap
Bower and Pulling in Components
We will need specific apply for our application like bootstrap and of course angular. We will tell bower to get those parts for us.
Bower is a fantastic frontend tool to manager your frontend resources. You simply define the plans you need and it will go grab them for you. Here’s a post on beginning with bower.
Initially we will require Bower installed on our maker. Just type in npm set up -g bower into your console.
After you have done that, you will now have access to bower worldwide on your system. We will need 2 files to get Bower working for us (. bowerrc and bower.json). We’ll position both of these in the root of our file.
. bowerrc will tell Bower where to place our files:
bower.json is similar to package.json and will inform Bower which plans are required.
“name”: “starter-node-angular”, “variation”: “1.0.0”, “dependences”: “bootstrap”: “most current”, “font-awesome”: “newest”, “animate.css”: “newest”, “angular”: “latest”, “angular-route”: “newest”
Let’s run it! In your console, in the root of your application, type:
bower install You can see bower pull in all the files we required and now we have them in public/libs!
Now we can get down to service and deal with our Angular things.
Establishing Our Angular Application
For our Angular application, we will want:
- 2 different pages (Home, Geeks)
- A different Angular controller for each
- An Angular service for Nerds
- No page revitalize when switching pages
Let’s produce the files needed for our Angular application. This will be carried out in public/js. Here is the application structure for our frontend:
– public —– js ———- controllers ——————– MainCtrl.js ——————– NerdCtrl.js ———- services ——————– NerdService.js ———- app.js ———- appRoutes.js
Once we have produced our controllers, services, and routes, we will combine them all and inject these modules into our primary app.js submit to get whatever working together.
We won’t go too far in depth here so let’s simply show off all three of our controllers and their code.
// public/js/controllers/ MainCtrl.js angular.module(‘MainCtrl’, . controller(‘MainController’, function($scope) $scope.tagline=’To the moon and back!’; );// public/js/controllers/ NerdCtrl.js angular.module(‘NerdCtrl’, . controller(‘NerdController’, function($scope) );
Obviously in the future you will be doing a lot more with your controllers, however because this is more about application setup, we’ll move onto the services.
This is where you would utilize $http or $resource to do your API calls to the Node backend from your Angular frontend.
// public/js/services/ NerdService.js angular.module(‘NerdService’, . factory(‘Geek’, [$http’, function($http) return call to ERASE a nerd erase: function(id) ‘ + id);];
That’s it for our services. The only function that will operate in that NerdService is the get function. The other two are simply placeholders and they won’t work unless you define those specific routes in your app/routes. js file. For more on building APIs, here’s a tutorial for Building a RESTful Node API.
These services will call our Node backend, retrieve information in JSON format, and after that we can utilize it in our Angular controllers.
Now we will specify our Angular paths inside of our public/js/appRoutes. js file.
// public/js/appRoutes. js angular.module(‘appRoutes’, . config( [$routeProvider’, ‘$locationProvider’, function($routeProvider, $locationProvider) ];
Our Angular frontend will use the template file and inject it into the
in our index.html file. It will do this without a page refresh which is exactly what we desire for a single page application.
For additional information on Angular routing and templating, take a look at our other tutorial: Single Page Apps with AngularJS.
Updated View Files
With all of the Angular routing ready to go, we simply require to develop the view files and then the smaller design template files (home.html, nerd.html, and geek.html) will be injected into our index.html file inside of the
Notification in our index.html file we are calling the resources we pulled in using bower.