Menu Home

How to build a blog with MongoDB, Express, Angular 2 and Node.js on Ubuntu – Part 1

Spread the love

One of the most common posts out there is the “How to build a blog in 15 minutes” it all started in Railscasts back in 2006. Since then I’ve seen several of them in languages as diverse as PHP, phyton, pearl, C# even C++ believe it or not.

In this tutorial, I will guide you step by step in how to build a blog with node.js. One of the most common node.js stacks out there is the MEAN stack. MEAN simply stands for MongoDB, Express, AngularJS and Node.js. You can get the original MEAN stack from mean.io it’s very easy to setup and there is a comprehensive guide on the website that you can follow.

In part 1 of this tutorial, I’m going to install all the pieces we need to get it all working. In part 2 we’ll build the blog.

Prerequisites

  • A freshly build ubuntu 16 machine, I will be using a Ubuntu Server 16.0.4 LTS virtual machine over ssh, you can use your local computer
  • A terminal application, I will use iTerm for mac
  • Understanding of running shell command

1. Install Node

We need node and npm, so let’s start by installing both of them. The are several different ways you can do this I’ll install it globally using the official repo and I’ll be using version 6.10.2 which is the latest LTS version.

First, add the PPA file

sudo apt-get install python-software-properties
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -

And then we can install it using apt-get

sudo apt-get install nodejs

Let’s test it all

node -v && npm -v

You should get something similar to this:

v6.10.2
3.10.10

2. Install MongoDB

For this tutorial, I’m using the standard version that can be installed with apt-get, there are several tutorials out there explaining how to install the official version.

sudo apt-get install mongodb

Now create the data folder

sudo mkdir -p /data/db

And start mongo

sudo systemctl start mongod

That’s it. Mongo is now running as a service and ready to use.

3. Install Angular

The next step is to start a new Angular 2 app. To do this we will need angular-cli (we don’t really need it but it’s easier like this).

npm install -g @angular/cli

Now we can start a new Angular app. Simply navigate to your projects folder and type:

ng new mean2 && cd mean2

you can test it by running

ng serve

Now open your browser in the link on your console and you should see this:

 4. Install Express

Next step is to install Express

npm install --save express body-parser

Then create a file named server.js and a folder named server in the root of your project

touch server.js && mkdir server

Now open server.js and add the following content

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

// Get our Blog routes
const blog = require('./server/routes/api/blog');

const app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
app.use('/api/blog', blog);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

The above code creates a simple express app with an /api/blog route pointing to server/routes/api/blog.js and a catch-all route. Please note that the catch-all rule is the last one. keep it like this or all the other routes will be ignored.

Now let’s create our basic JSON response in our blog route.

Create a file named blog.js inside server/routes/api and had this content

const express = require('express');
const router = express.Router();

let responseJSON = {
    'posts': []
};

/* GET blog listing. */
router.get('/', (req, res) => {
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify(responseJSON));
});

module.exports = router;

We’re almost ready t0 test. Because we defined our catch-all route to point to dist/index.html we need to build the Angular 2 app. Just run

ng build

This will create a dist folder and compile your angular app.

All that is left to do is start your express application

node server.js

if you navigate to http://localhost:3000/ you should get

and if you navigate to http://localhost:3000/api/blog

That’s it. In part 2 of this tutorial, we will be building a blog using and storing all the data in MongoDB.

Categories: Tutorials

Tagged as:

Claudio Pinto

Leave a Reply

Your email address will not be published. Required fields are marked *