Express.js & Node.js Course for Beginners - Full Tutorial

Learn how to develop a web app from scratch using Node.js, Express.js, PostgreSQL, and Bootstrap. Develop a landing page and a CRUD application collecting sales leads.


The code from this project is a good starting place for you to develop your own project.

💻Code: https://github.com/buzz-software/expressjs-mvp-landing-page



Secure Node.js, Express.js and PostgreSQL API using Passport.js

Secure Node.js, Express.js and PostgreSQL API using Passport.js

The comprehensive step by step tutorial on building secure Node.js, Express.js, Passport.js, and PostgreSQL Restful Web Service

The comprehensive step by step tutorial on building secure Node.js, Express.js, Passport.js, and PostgreSQL Restful Web Service. Previously, we have shown you a combination of Node.js, Express.js, and PostgreSQL tutorial. Now, we just add a security for that RESTful Web Service endpoints. Of course, we will start this tutorial from scratch or from zero application. We will use JWT for this Node.js, Express.js, Passport.js, and PostgreSQL tutorial.

Table of Contents:

The following tools, frameworks, and modules are required for this tutorial:

We assume that you have installed PostgreSQL server in your machine or can use your own remote server (we are using PostgreSQL 9.5.13). Also, you have installed Node.js in your machine and can run node, npm or yarn command in your terminal or command line. Next, check their version by type this commands in your terminal or command line.

node -v
v8.12.0
npm -v
6.4.1
yarn -v
1.10.1

That the versions that we are uses. Let’s continue with the main steps.

1. Create Express.js Project and Install Required Modules

Open your terminal or node command line the go to your projects folder. First, install express generator using this command.

sudo npm install express-generator -g

Next, create an Express.js app using this command.

express secure-node --view=ejs

This will create Express.js project with the EJS view instead of Jade view template because using ‘–view=ejs’ parameter. Next, go to the newly created project folder then install node modules.

cd secure-node && npm install

You should see the folder structure like this.

There’s no view yet using the latest Express generator. We don’t need it because we will create a RESTful API.

2. Add and Configure Sequelize.js Module and Dependencies

Before installing the modules for this project, first, install Sequelize-CLI by type this command.

sudo npm install -g sequelize-cli

To install Sequelize.js module, type this command.

npm install --save sequelize

Then install the module for PostgreSQL.

npm install --save pg pg-hstore

Next, create a new file at the root of the project folder.

touch .sequelizerc

Open and edit that file then add this lines of codes.

const path = require('path');

module.exports = {
  "config": path.resolve('./config', 'config.json'),
  "models-path": path.resolve('./models'),
  "seeders-path": path.resolve('./seeders'),
  "migrations-path": path.resolve('./migrations')
};

That files will tell Sequelize initialization to generate config, models, seeders and migrations files to specific directories. Next, type this command to initialize the Sequelize.

sequelize init

That command will create config/config.json, models/index.js, migrations and seeders directories and files. Next, open and edit config/config.json then make it like this.

{
  "development": {
    "username": "djamware",
    "password": "[email protected]@r3",
    "database": "secure_node",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "test": {
    "username": "root",
    "password": "[email protected]@r3",
    "database": "secure_node",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "production": {
    "username": "root",
    "password": "[email protected]@r3",
    "database": "secure_node",
    "host": "127.0.0.1",
    "dialect": "postgres"
  }
}

We use the same configuration for all the environment because we are using the same machine, server, and database for this tutorial.

Before run and test connection, make sure you have created a database as described in the above configuration. You can use the psql command to create a user and database.

psql postgres --u postgres

Next, type this command for creating a new user with password then give access for creating the database.

postgres-# CREATE ROLE djamware WITH LOGIN PASSWORD '[email protected]@r3';
postgres-# ALTER ROLE djamware CREATEDB;

Quit psql then log in again using the new user that previously created.

postgres-# \q
psql postgres -U djamware

Enter the password, then you will enter this psql console.

psql (9.5.13)
Type "help" for help.

postgres=>

Type this command to creating a new database.

postgres=> CREATE DATABASE secure_node;

Then give that new user privileges to the new database then quit the psql.

postgres=> GRANT ALL PRIVILEGES ON DATABASE secure_node TO djamware;
postgres=> \q

3. Create or Generate Models and Migrations

We will use Sequelize-CLI to generating a new model. Type this command to create a model for Products and User model for authentication.

sequelize model:create --name Product --attributes prod_name:string,prod_desc:string,prod_price:float
sequelize model:create --name User --attributes username:string,password:string

That command creates a model file to the model’s folder and a migration file to folder migrations. Next, modify models/user.js and then import this module.

var bcrypt = require('bcrypt-nodejs');

Add the new methods to the User model, so the user.js class will be like this.

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    username: DataTypes.STRING,
    password: DataTypes.STRING
  }, {});
  User.beforeSave((user, options) => {
    if (user.changed('password')) {
      user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);
    }
  });
  User.prototype.comparePassword = function (passw, cb) {
    bcrypt.compare(passw, this.password, function (err, isMatch) {
        if (err) {
            return cb(err);
        }
        cb(null, isMatch);
    });
  };
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

For the models/product.js there’s no action needed, leave it as default generated the model class.

4. Create Routers for RESTful Web Service and Authentication

To authenticating users and secure the resources or endpoint create this file as a router.

touch routes/api.js

Open and edit routes/api.js then declares all require variables.

const express = require('express');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const router = express.Router();
require('../config/passport')(passport);
const Product = require('../models').Product;
const User = require('../models').User;

Create a router for signup or register the new user.

router.post('/signup', function(req, res) {
  console.log(req.body);
  if (!req.body.username || !req.body.password) {
    res.status(400).send({msg: 'Please pass username and password.'})
  } else {
    User
      .create({
        username: req.body.username,
        password: req.body.password
      })
      .then((user) => res.status(201).send(user))
      .catch((error) => {
        console.log(error);
        res.status(400).send(error);
      });
  }
});

Create a router for sign in or login with username and password.

router.post('/signin', function(req, res) {
  User
      .find({
        where: {
          username: req.body.username
        }
      })
      .then((user) => {
        if (!user) {
          return res.status(401).send({
            message: 'Authentication failed. User not found.',
          });
        }
        user.comparePassword(req.body.password, (err, isMatch) => {
          if(isMatch && !err) {
            var token = jwt.sign(JSON.parse(JSON.stringify(user)), 'nodeauthsecret', {expiresIn: 86400 * 30});
            jwt.verify(token, 'nodeauthsecret', function(err, data){
              console.log(err, data);
            })
            res.json({success: true, token: 'JWT ' + token});
          } else {
            res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
          }
        })
      })
      .catch((error) => res.status(400).send(error));
});

Create a secure router to get and post product data.

router.get('/product', passport.authenticate('jwt', { session: false}), function(req, res) {
  var token = getToken(req.headers);
  if (token) {
    Product
      .findAll()
      .then((products) => res.status(200).send(products))
      .catch((error) => { res.status(400).send(error); });
  } else {
    return res.status(403).send({success: false, msg: 'Unauthorized.'});
  }
});

router.post('/product', passport.authenticate('jwt', { session: false}), function(req, res) {
  var token = getToken(req.headers);
  if (token) {
    Product
      .create({
        prod_name: req.body.prod_name,
        prod_desc: req.body.prod_desc,
        prod_price: req.body.prod_price
      })
      .then((product) => res.status(201).send(product))
      .catch((error) => res.status(400).send(error));
  } else {
    return res.status(403).send({success: false, msg: 'Unauthorized.'});
  }
});

Create a function for extract the token.

getToken = function (headers) {
  if (headers && headers.authorization) {
    var parted = headers.authorization.split(' ');
    if (parted.length === 2) {
      return parted[1];
    } else {
      return null;
    }
  } else {
    return null;
  }
};

Finally, export the router as a module.

module.exports = router;

5. Run and Test Secure Node.js, Express.js, Passport.js, and PostgreSQL Web Service

To run and test this secure Node.js, Express.js, Passport.js, and PostgreSQL Web Service, run the PostgreSQL instance first then run this command from the Terminal.

nodemon

or

npm start

To test the secure Product endpoint, open the Postman then type fill all required fields like this image.

You should get the response message Unauthorized and status code 401. Next, test signup using the Postman by changing the method to POST, add the address localhost:3000/api/signup, add the header Content-type with value application/json and the body of request raw text like this.

{ "username":"[email protected]", "password":"qqqq1111" }

You should get this response when executing successfully.

Next, test to log in with the above signed/registered username and password by changing the URL to localhost:3000/api/signin. You should get this response when executes successfully.

Now, you can back using the previous GET method with additional header using the token get from the sign in/log in response. You should see the Product data like below.

That it’s, the secure Node.js, Express.js, Passport.js, and PostgreSQL Web Service. You can get the working source code from our GitHub.

Learn More

The Complete Node.js Developer Course (2nd Edition)

Learn and Understand NodeJS

Node JS: Advanced Concepts

GraphQL: Learning GraphQL with Node.Js

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

The Complete Python & PostgreSQL Developer Course

SQL & Database Design A-Z™: Learn MS SQL Server + PostgreSQL

The Complete SQL Bootcamp

The Complete Oracle SQL Certification Course

Security Best Node.js - Managing Sessions in Express.js

Security Best Node.js - Managing Sessions in Express.js

Every user interaction with your application is an isolated and individual request and response. The need to persist information between requests is vital for maintaining the ultimate experience for the user and the same applies for Node.js web...

Every user interaction with your application is an isolated and individual request and response. The need to persist information between requests is vital for maintaining the ultimate experience for the user and the same applies for Node.js web application such as the popular Express.js framework.

A common scenario that most developers can identify with is the need to maintain that a user has authenticated with an application.  In addition, it’s quite common to retain various personalized user information that is associated with a session as well.

Similarly, we are going to look at how we can securely set up sessions in our application to mitigate risks such as session hijacking. We’re going to look at how we can obfuscate session ID’s, enforce a time-to-live in our sessions, set up secure cookies for transporting sessions, and finally the importance and role of Transport Layer Security (TLS) when it comes to using sessions.

Setting of Sessions in Express.js

We’re going to use the NPM module express-sessions, a very popular session module that has been highly vetted by the community and constantly improved.

We’ll pass our express app object to a function to wire up the express-session module:

"use strict";
// provides a promise to a mongodb connection
import connectionProvider            from "../data_access/connectionProvider";
// provides application details such as MongoDB URL and DB name
import {serverSettings}              from "../settings";
import session                       from "express-session";
import mongoStoreFactory             from "connect-mongo";

export default function sessionManagementConfig(app) {

    // persistence store of our session
    const MongoStore = mongoStoreFactory(session);

    app.use(session({
        store: new MongoStore({
            dbPromise: connectionProvider(serverSettings.serverUrl, serverSettings.database)
        }),
        secret: serverSettings.session.password,
        saveUninitialized: true,
        resave: false,
        cookie: {
            path: "/",
        }
    }));

    session.Session.prototype.login = function(user, cb){
        this.userInfo = user;
        cb();
    };
}
What’s Going On Here

We're importing the session function from the express-session NPM module and passing the session function a configuration object to set properties such as:

  • **Store. **I’m using MongoDB as my backend, and I want to persist the application sessions in my database, so I am using the connect-mongo NPM module and setting the session store value to an instance of this module. However, you might be using a different backend, so your store option could be different. The default for express-session is an in-memory storage.

  • Secret. This is a value used in the signing of the session ID that is stored in the cookie.

  • Cookie. This determines the behavior of the HTTP cookie that stores the session ID.

We will come back to some of the elements I didn’t mention here shortly.  For now, let’s look at the first change we need to make with securely managing user sessions in our application.

Session Hijacking

The most prevalent risk that user sessions face is session hijacking. Sessions are much like a driver’s license or passport and provide identification for our users. If an attacker can steal the session of another user, they have essentially become that other person and can exploit the user or perform malicious activity on behalf of that user. The risk is even greater when the identity is someone with escalated privilege such as a site admin.

Session Identification

The first step that any attacker will perform is reconnaissance to determine where vulnerabilities lie in your application. Part of that reconnaissance is observing tell-tale signs of the underlying framework, third-party modules and any other software that in itself might contain vulnerabilities that can be exploited.

In the case of our sessions, a tell-tale sign is the name of the session cookie connect.sid, which can help an attacker identify the session mechanism being used and look for specific vulnerabilities.

Tip: Of course we don’t want to use vulnerable software. However, secure software today could be vulnerable tomorrow with a faulty update. So, keeping details about our application obfuscated can help make it that much more difficult for an attacker to exploit.

Therefore, the first thing we want to do is make that as hard to determine what session mechanism is used as possible, let’s update our session configuration object with a name property:

 app.use(session({
        store: new MongoStore({
            dbPromise: connectionProvider(serverSettings.serverUrl, serverSettings.database)
        }),
        secret: serverSettings.session.password,
        saveUninitialized: true,
        resave: false,
        cookie: {
            path: "/",
        }

       name: "id"
    }));

What Did We Do?

By providing a name property with a value of ID, it will be that much more difficult for any attacker to determine the underlying mechanisms used by our application.

Now that we have provided a level of obfuscation to our sessions, let’s look at how we can reduce the window of opportunity for session hijacking.

Session Time-to-Live

Unfortunately, sometimes the best-laid plans can be undermined. A perfect example is a user who didn’t log off a public computer and an attacker who was able to physically obtain access and operate as the previous user.

Therefore, we can reduce the window that the session is alive and directly impact the chances that an attacker can exploit a user or the system from a hijacked session by limiting the life of a session.

As I mentioned before, the express-sessions NPM module provides a store property where you can set a separate storage mechanism for storing your sessions (the default is in-memory). Therefore, the following change is tied to your backend storage of sessions. In my case, I am storing my sessions in a MongoDB database, and using the NPM module connect-mongo for easily storing sessions in the database.

In this case, I can provide the ttl property a value in seconds in the configuration object provided to the MongoStore, the default is 14 days (142460*60):

app.use(session({
   store: new MongoStore({
       dbPromise: connectionProvider(serverSettings.serverUrl, serverSettings.database),
       ttl: (1 * 60 * 60)
   }),
   //remaining - removed for brevity
}));

Cookie Time-to-Live

Not nearly as important as the session’s TTL, we can also set the expiration of the cookie, which is used for transporting the session ID, in the session configuration object.
We can provide a maxAge property and value in milliseconds in the cookie object.

app.use(session({
       //..previous removed for brevity

        cookie: {
            path: "/“,
       maxAge:  1800000  //30 mins
        }
}));

However, security and user experience is always a balancing act and in this case, reducing the time-to-live of the session will directly affect the user experience of when the user will be required to re-authenticate.

Tip: The most important thing is the life of the session, so whether you set a cookie’s age, you should never rely on it by itself and should always regulate the session’s time-to-live. One way to counterbalance the user’s experience is to require re-authenticating at the time that user’s attempt to access key access area’s of your site.

Regenerating New Sessions

It’s common practice to associate a session with an anonymous user, one who hasn’t authenticated with your application. However, when a user does successfully authenticate with your application, it is absolutely paramount that the authenticated user doesn’t continue to use the same session ID.

There are a number of creative ways attackers can obtain an authenticated user’s session, especially when sites make it easy by transporting the session ID in the URL.  In the case that an unauthenticated session had been hijacked by an attacker, when the legitimate user authenticates with the site, and the site has allowed the user to continue using the same session ID, the malicious user will also find that the session they had hijacked is now an authenticated session, allowing them to operate as the user.

You’ll notice in the original function where we wired up our Sessions, we’re adding a Login method to the Session’s prototype so it’s available to all instances of a Session object.

session.Session.prototype.login = function(user){
        this.userInfo = user;
};

This is simply a convenience method that I can access to associate user information with a user session, such as in the case of an authentication route API. For example, like we saw back in Node.js and Password Storage with Bcrypt, following a successful login, we have access to the session object off the request.

authenticationRouter.route("/api/user/login")
    .post(async function (req, res) {
        try {

          //removed for brevity….

          req.session.login(userInfo, function(err) {
            if (err) {
               return res.status(500).send("There was an error logging in. Please try again later.");
            }
          });
        //removed for brevity….
     });

However, it’s absolutely paramount not to continue using the same session ID after a user has successfully authenticated.  The express-sessions module provides a convenient regenerate method for regenerating the session ID. Our loginprototype method off of the Session object is a convenient place for regenerating the Session ID, so let's update:

session.Session.prototype.login = function (user, cb) {
   const req = this.req;
   req.session.regenerate(function(err){
      if (err){
         cb(err);
      }
   });

   req.session.userInfo = user;
   cb();
};

Now, when we provide information to be associated with a user’s session following the user’s successful authentication with our application, we can also ensure that a new session has been generated for this user.

Since cookies are what we use to transport our sessions, it’s important to implement secure cookies.  Let’s look at how we can do that next.

Cookies

We use sessions to maintain state between user requests and we use cookies to transport the session ID between those requests. You probably don’t drive through shady neighborhoods without locking your doors, nor should you throw your sessions out in the wild without any protection.

There are primarily 3 ways to protect the cookie, 2 that we will look at here, and a third we’ll examine in the next section when we look at serving our application content over HTTPS.

HTTPOnly Flag

Since the session ID is of no use to the client, there is absolutely no reason that the front-end application should ever have access to the session ID in the cookie.  However, by default, any script running on the front-end application will have access to a cookie’s contents.

We can limit access to our session cookie’s content by issuing the HTTP Set-cookie header and specifying the HTTPOnly flag for our session cookie.

HTTP header:

Set-cookie: mycookie=value; path=/; HttpOnly

We can easily provide this header by simply setting the httpOnly property on our cookie object to “true:”

app.use(session({
       //..previous removed for brevity

        cookie: {
            path: “/“,
            httpOnly: true,
       maxAge:  1800000
        }
}));

Now, only the agent (i.e., browser) will have access to the cookie in order to resubmit it on the next request to the same domain. This will directly help mitigate cross-site scripting threats that could have otherwise accessed the contents of our session cookie.

Secure Flag

With the HTTPOnly flag set, we limited application scripts from accessing our cookies at the front-end application, but what we haven’t stopped is prying eyes.

Man-in-the-middle (MitM) attacks are common and can easily be carried out by anyone that has access to the network traffic.  This goes along with any local coffee house WIFI that users might typically use.  If your session information is sent over the network without being encrypted, that information is available to anyone listening to the network traffic.

In addition to the HTTPOnly flag we specified, we can also set the Secure flag on our Set-CookieHTTP Header. This will notify the agent (i.e., browser) that we don’t want to send our cookie on any HTTP requests unless it is a secure connection.

HTTP header:

Set-cookie: mycookie=value; path=/; HttpOnly secure

Again, we can easily do so by setting the secure property on our cookie object to “true:”

app.use(session({
       //..previous removed for brevity

        cookie: {
            path: “/“,
            httpOnly: true,
            secure: true,
            maxAge:  1800000
        }
}));

In addition, a common scenario that the secure flag helps prevent is the risk of mixed content. It’s quite common to easily have a page or site setup to use secure HTTP (HTTPS), but an individual resource on that page is being requested insecurely over HTTP.

Without the Secure flag, that HTTP request would have leaked our session cookie on that insecure request for that resources.

Tip: Content Security Policies can help report when a page consist of mixed content. In a future post, we’ll look at how content security policies (CSP) can help to address mixed-content issues.

Unfortunately, with the Secure flag set, unless we are serving our page or site over HTTPS, we have eliminated the ability to send our session cookie on each request and that’s definitely not something we want. So, in the final section, let’s look at the importance of using Transport Layer Security (TLS) when it comes to securely managing our user sessions.

Transport Layer Security

We mentioned the risk of man-in-the-middle attacks earlier and how anyone with the means can easily listen to all network traffic. However, because the traffic is insecure and not encrypted, they can also eavesdrop on the information in that traffic.

I have already covered the underlying details about TLS and since this isn’t strictly an article on TLS, I’m not going to rehash those details here. However, no topic on session management would be complete without mentioning the role and importance of TLS when it comes to securing user sessions.

If we only ever want to send our highly sensitive session cookies over a secure connection, then we must serve those requests and pages over an HTTP connection using Transport Layer Security (HTTPS).

TLS provides a number of benefits such as integrity of the information being exchanged and validity of the server you’re communicating with. In addition, transport layer security provides confidentiality of the information being exchanged through the means of encryption. Serving your site's content over TLS can ensure that your sensitive session cookie is encrypted and not viewable by the prying eyes of a man-in-the-middle attack.

In a future post, we’ll look at the details of serving our Node.js application over HTTPS.

Conclusion

Sessions are still a highly prominent tool for maintaining user state in a very stateless environment. However, sessions are usually tightly tied to sensitive data such as authentication and identification information regarding the user. Therefore, it is absolutely paramount to implement the necessary mitigations to protect against risks such as session hijacking as well as related threats that can lead to sessions hijacking such as man-in-the-middle and cross-site scripting attacks.

Thank you for reading !

Fullstack Vue App with MongoDB, Express.js and Node.js

Fullstack Vue App with MongoDB, Express.js and Node.js

In this article, you'll learn building a fullstack Vue note-taking application and showing you how to perform the aforementioned processes, using Node.js running the Express.js framework for the back end, and MongoDB to store our data.

In this article, you'll learn building a fullstack Vue note-taking application and showing you how to perform the aforementioned processes, using Node.js running the Express.js framework for the back end, and MongoDB to store our data.

We learn how to create full fledge application using this increasingly popular tech stack that takes advantage of the upstart Vue.js.

Much of application development, including web applications, has to do with CRUDcreating, reading, updating, and deleting data.

Below is a preview of the application we will be building:

Configuring the Development Environment

For this tutorial, I will be using the Eclipse IDE with the CodeMix plugin installed.

Getting Started

Now we can create our project using the Eclipse IDE, by navigating to File > New > Project. Select the **Vue **option under the CodeMix list of projects, name the application, and click Next to proceed (make sure to be connected to the Internet to enable CodeMix, to get the newest Vue.js template and folder structure for the application), as shown below:

Open the integrated Terminal+ in CodeMix 2.0. Alternatively, it can be opened using the command Ctrl + Shift + P, as shown below:

After that has been completed, we make some changes in the folder structure. First, we add an API folder in the root folder of our project. This folder would contain the Express backend (which includes the server.js file). In the terminal, we run the following commands to install the required modules for the application:

npm install 
npm install --save axios body-parser cors express mongoose moment

  • Axios – a promise-based HTTP client that we will use to communicate with the Node server.
  • Body-parser – a Node.js middleware for parsing request inputs.
  • CORS – middleware that is used to enable Cross-Origin Resource Sharing.
  • Mongoose – an Object Data Modeling (ODM) library for MongoDB.
  • Moment – a library used to parse and format dates.

Next, we add the following line in the scripts object in the package.json file:

...
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "api": "node api/server.js"
  }
...

Running Our Backend and Front-End

Wait, already? Isn’t it too early to run these applications before writing any code? Actually, it isn’t – with the following scripts running, your code will be watched for changes, and the running backend and front-end applications will be automatically updated when necessary.

We can start the Vue.js application using this command in the terminal:

npm run serve

Your browser will automatically open to http://localhost:3000, where you can see the Vue app slowly take shape as we add more code.

And let’s start the back end by using the command below in a different terminal (simply use the +button in the Terminal+ view to open a new terminal tab for the same project):

npm run api

Building the Backend With Node.js and Express.js

Creating the Note Model

Before setting up the actual server, let’s create the Note model, which is the only model for this application. A model is an object representation of the data in a database. Here, using Mongoose we can specify a schema of data as well; this helps with the validation of the data. In the folder, we create a new Note.js file that will contain the code below:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const NoteSchema = Schema(
    {
        title: {type: String, required: true},
        body: {type: String, required: true},
    }, 
    { timestamps: true }
);
const Note = mongoose.model("Note", NoteSchema);
module.exports = Note;

The first parameter object describes the fields, their types, and constraints. The second parameter object of the schema constructor helps create a timestamp, i.e. two auto fields: createdAt which is set at data creation, and updatedAt which is set every time the data is modified.

Creating the Node.js Server

Next up, we create a server.js file in the API folder. This file will contain the Node.js configurations, as well as the routes we will be using in the application. The file will contain the code below:

'use strict';
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
//models
const Note = require('./Note');
//connect server to mongoDB 
+mongoose.connect(
  'mongodb://localhost:27017/simple_blog', 
  { useNewUrlParser: true, useCreateIndex: true, }
);
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
// retrieves all the notes
app.get('/api/note/list', (req, res) => {
  Note.find({}).sort({updatedAt: 'descending'}).exec((err, notes) => {
    if (err) return res.status(404).send('Error while getting notes!');
    return res.send({notes});
  });
});
// create a new note
app.post('/api/note/create', (req, res) => {
  const note = new Note({body: req.body.body, title: req.body.title});
  note.save( (err) => {
    if (err) return res.status(404).send({message: err.message});      
    return res.send({ note });
  });
});
// update an existing note with the given object id
app.post('/api/note/update/:id', (req, res) => {
let options = { new: true };
  Note.findByIdAndUpdate(req.params.id, req.body.data , options, (err, note) => {
    if (err) return res.status(404).send({message: err.message});
    return res.send({ message: 'note updated!', note });
  });
});
// delete an existing note with the given object id
app.post('/api/note/delete/:id', (req,res) => {
  Note.findByIdAndRemove(req.params.id, (err) => {
    if (err) return res.status(404).send({message: err.message});
    return res.send({ message: 'note deleted!' });
  });
});
const PORT = 5000;
app.listen(PORT);
console.log('api runnging on port ' + PORT + ': ');

The server.js module helps set up a simple connection to MongoDB using a Mongoose method, while also listening for an error event on connecting to the database (which can be caused by improper installation or unavailability of *MongoDB *on the computer). The server.js also applies the necessary middlewares to the *Express server *and provides four routes. The first route fetches all the notes in the *database *using the note model. The second route will allow the creation of a new note. The third route updates a note of a given ID which is passed as the route parameter; it also returns the updated note which, as a result of the options object, is passed to the findByIdAndUpdate method. The last route deletes a note with the ID passed in the parameter of the route.

Building the Front-End With Vue.js

Web Service Calls With Axios

After we have completed the server part of the application, we can proceed to create the repository.js file in the src folder. This file will contain all the server calls we would be making from the Vue.js application using the Axios module. The file code is below:

import axios from 'axios';
const BASE_URL = 'http://localhost:5000';
export function getNotes() {
        return axios.get(`${BASE_URL}/api/note/list`)
                .then(response => response.data);
}
export function deleteNote(id){
        return axios.post(`${BASE_URL}/api/note/delete/${id}`)
                .then(response => response.data)
                .catch(err => Promise.reject(err.message));
}
export function createNote(data) {
        return axios.post(`${BASE_URL}/api/note/create`, 
        { title: data.title, body: data.body }
        )      .then(response => {
                        return response.data
                })
                .catch(err => Promise.reject(err.message));
}
export function updateNote(data, id) {
        return axios.post(`${BASE_URL}/api/note/update/${id}`, { data })
                .then(response => {
                        return response.data
                })
                .catch(err => Promise.reject(err.message));
}

The application is styled using the Bulma CSS framework that is added to the public/index.html file in the head tag, as written below:

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.css">

Creating the Root Component

Next, we proceed to edit the App component, which is the entry component for the Vue.js application. In this file, we add the application header and render a couple of components that we will be building later in this article. The src/App.vue component also provides some methods which manage the application data. This component also loads the list of available notes in the database when the component has been mounted (loaded); it does this using the getNotes function provided in the repository.js module.

If you use CodeMix, you can see below how you will be able to edit the .vue files – these files allow you to keep the HTML, JavaScript, and styles of a component in a single place, and the editor provides content assist and validation corresponding to the section you are in. Have a look at these quick GIFs to see the .vue editor in action.

This App.vue file contains the code below:

<template>
  <div id="app">
    <nav class="navbar is-light" role="navigation" aria-label="main navigation">
      <div class="container">
        <div class="navbar-brand">
          <a class="navbar-item" href="#">
            <span class="title is-size-1">NoteTaker</span>
          </a>
        </div>
      </div>
    </nav>
    <br><br>
    <div  class="container">
      <div v-if="notes">
        <CreateNoteModal @createNote="createNote"/>
        <br>
        <div>
          <noteItem v-for="(note, index) in notes" :note="note" :key="index" @deleteNote="deleteNote" @updateNote="updateNote"/>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import NoteItem  from './components/NoteItem.vue'
import CreateNoteModal  from './components/CreateNoteModal.vue'
import { getNotes }  from './repository'
export default {
  name: 'app',
  components: { NoteItem, CreateNoteModal  },
  data(){
    return {
      notes: []
    }
  },
  methods: {
    deleteNote(id){
      let notes = this.notes.filter(note => note._id != id)
      this.notes = notes;
    },
    updateNote(note){
      this.deleteNote(note._id);
      this.createNote(note);
    },
    createNote(note){
        this.notes = [note, ...this.notes];
    },
  },
  mounted(){
    getNotes()
      .then(data => this.notes = data.notes)
      .catch((err =>alert(err)));
  }
}
</script>

Creating Components

Next, we create the CreateNoteModal component in the src/components/CreateNoteModal.vue, which contains the code below:

<template>
  <div>
    <div class="modal" :class="{ 'is-active': isActive }">
      <div class="modal-background"></div>
      <div class="modal-card">
        <header class="modal-card-head">
          Add Note
        </header>
        <section class="modal-card-body">
          <div class="field">
            <div class="control">
              <input v-model="title" class="input" type="text" placeholder="title">
            </div>
          </div>
          <div class="field">
            <div class="control">
              <textarea v-model="body" class="textarea"  placeholder="enter content">
                </textarea>
            </div>
          </div>
          <button @click="create" class="button is-primary is-pulled-right">Post</button>
        </section>
      </div>
      <button @click="toggle" class="modal-close is-large" aria-label="close"></button>
    </div>
    <button @click="toggle" class="button is-primary is-pulled-right">Create Note</button>
    <br>
  </div>
</template>
<script>
import { createNote }  from '../repository'
export default {
  name: 'CreateNoteModal',
  data(){
    return {
      title: '',
      body: '',
      isActive: false
    }
  },
  methods: {
    create(){
      let data = { title: this.title, body: this.body }
      createNote(data)
        .then(data => {
          this.$emit('createNote', data.note);
          this.title = this.body = '';
          this.toggle();
        })
        .catch(err => alert(err.message));
    },
    toggle(){
      this.isActive = !this.isActive;
    },
  },
}
</script>

This component is a form in a modal with both input in the form, title, and body, bound to the component’s data with corresponding names. The submit button calls the create method which makes the server call, passing the data to the createNote function from the repository.js module. Upon a successful server request, this method emits a custom event that is handled by the parent component (which in this case is the App.vue component). It also clears the form and closes the modal.

Next up, we create the NoteItem component in the src/components/NoteItem.vue, which contains the code below:

<template>
  <article class="message">
    <div class="message-header">
      <p>{{ note.title }}</p>
      <button @click="deleteNote" class="delete" aria-label="delete"></button>
    </div>
    <div class="message-body">
      {{ note.body }}
      <br>
      <br>
      <span class="has-text-grey-light">Created at: {{ note.createdAt | moment }}</span>
      <br>
      <span class="has-text-grey-light">last updated: {{ note.updatedAt | moment }}</span><br>
      <UpdateNoteModal :note="note" @updateNote="updateNote" :key="note._id"/>
    </div>
  </article>
</template>
<script>
  import { deleteNote } from '../repository'
  import UpdateNoteModal from './UpdateNoteModal'
  import Moment from 'moment'
  export default {
    name: 'NoteItem',
    props: [ 'note' ],
    components: { UpdateNoteModal },
    methods: {
      deleteNote(e){
        e.preventDefault();
        deleteNote(this.note._id)
          .then(() => this.$emit('deleteNote', this.note._id))
          .catch(err => alert(err))
      },
      updateNote(note){
        this.$emit('updateNote', note)
      }
    },
    filters: {
      moment(date) {
        return Moment(date).format('MMMM Do YYYY, h:mm:ss a');
      }
    }
  }
</script>

This module renders each note, which is passed to it by its parent component (App.vue). It also provides two methods, the first of which is the deleteNote, which deletes the given note using the deleteNote function from the repository.js by passing the note ID to it. Upon success, it emits a custom deleteNote event to the parent component, which deletes the note from the array of notes.

The second method, updateNode, emits an updateNode event in response to the same event name, emitted by its child component, UpdateNoteModal, which we will create next. It also provides a moment date-time filter using the Moment module to format the date for the component.

Finally, we create the UpdateNoteModal component in the src/components/UpdateNoteModal.vue, which contains the code below:

<template>
  <div>
    <div class="modal" :class="{ 'is-active': isActive }">
      <div class="modal-background"></div>
      <div class="modal-card">
        <header class="modal-card-head">
          Update Note
        </header>
        <section class="modal-card-body">
          <div class="field">
            <div class="control">
              <input v-model="title" class="input" type="text" placeholder="title">
            </div>
          </div>
          <div class="field">
            <div class="control">
              <textarea v-model="body" class="textarea"  placeholder="enter content"></textarea>
            </div>
          </div>
          <button @click="update" class="button is-primary is-pulled-right">Post</button>
        </section>
      </div>
      <button @click="toggle" class="modal-close is-large" aria-label="close"></button>
    </div>
    <button @click="toggle" class="button is-small is-pulled-right">Update</button>
  </div>
</template>
<script>
import { updateNote }  from '../repository'
export default {
  name: 'UpdateNoteModal',
  data(){
    return {
      title: this.note.title,
      body: this.note.body,
      isActive: false
    }
  },
  props: ['note'],
  methods: {
    update(){
      let data = { title: this.title, body: this.body }
      updateNote(data, this.note._id)
        .then(data => {
          this.$emit('updateNote', data.note);
          this.toggle();
        })
        .catch(err => alert(err.message));
    },
    toggle(){
      this.isActive = !this.isActive;
    },
  },
}
</script>

This, much like the CreateNoteModal, is a Bulma styled modal, which has two inputs whose values are bound to the component data, which is initialized using the note passed through to the component as a property. It also provides an update method, which is called when the post button is clicked. This method uses the updateNote function from the repository.js module to update the note. Upon a successful request, it emits an event – the updateNote event, which is handled by the parent component (i.e. the NoteItem component, which further passes it to the App component).

We did it, our note taking app is complete! Remember, if you haven’t already run your backend and front-end applications, please scroll back to the Running our Backend and Front-End sections for instructions.

Next Steps

To keep focused on the concepts being demonstrated, we’ve developed a simplified application. Here are some additional steps that would take our application to the next level:

  • Add authentication – Although the application performs the basic functions of a note-taking application and the four fundamental **CRUD **operations, it does not perform any form of authentication.
  • Folder structure – The folder structure is not suitable for larger applications, for example, the routes are usually in a separate file from the server configuration, and the models are usually grouped in a folder.
  • Vuex – Better stage management is possible by using a framework like Vuex.

The code for this application can be downloaded here.