Logo
UI Development

Up and running with MEVN – Part 1

Before getting started, I would like to provide the following information on 4 parts of Up and running with MEVN.

Part 1 – Dealing with the complete setup (vue, node, express, mongo), Sending response data from backend using Postman, fetching the data by frontend using Axios API.

Part 2 – Complete CRUD Functionality with an Example.

Part 3 – Setting up Authentication using Passport.js (SSO login).

Part 4 – Creating a separate channel with set of Authenticated users where you can post data and retrieve information what others have posted.

Example I am dealing with is TO-DO (Web-application).

So, Let’s get started with the Part 1

MEVN stands for “MongoDB Express.js Vue.js Node.js”.

MongoDB: A general purpose, document-based open source database.

Express.js: Uses HTTP Utility Methods to create Middleware for the application.

Vue.js: An open-source Model-view-viewmodel Frontend framework for creating user interfaces and Single page Applications.

Node.js: Node is a runtime system used for server side scripting using javascript.

Before setting up with MEVN, you must be aware of the following.

  • Basic understanding of Javascript.
  • Knowledge on Database Management.
  • REST and CRUD Concepts.
  • Node.js, MongoDB Installation.
  • Knowledge on Postman.

Why MEVN? (Here is my answer)

Being a Front-end Web-developer, I have almost zero knowledge on .net, PHP and basic understanding on JAVA concepts.

While exploring full-stack development framework for a small project I thought of going with MEAN or MERN or MEVN. I have chosen VueJS over React/Angular as Vue provides higher customizability and hence it is easier to learn than Angular or React.

The best thing about MEVN is, It uses only one language through out the application i.e., JavaScript.

Points to be discussed:

  • Client side setup (Frontend) using VUEJS
  • CRUD Operations (Middleware) using Express.js
  • Server side setup (Backend) using Node.js
  • Data storage and manipulation using MongoDB
  • API calls using Axios

Getting Started with Frontend:

First, Let us create a Folder and name it as project1. Now, open it using any code editor.

I prefer VS Code. Here are some of the plugins which make your job easy working with Vue.

  • Vetur – Used for Syntax highlighting, code snippets and many more.
  • Prettier – Used for code Formatting.
  • Vue-beautify – Beautifies Vue code in VS Code.
  • GitLens – It’s a very useful plugin. It adds all the git capabilities into VS Code and visualizes code authorship at a glance.
  • Javascript (ES6) code Snippets.

We will be using vue-cli to create the boiler plate.

npm i -g vue vue-cli

Now, create a folder named frontend inside folder project1.

vue init webpack frontend

Customize the project as per the project requirements.

PS D:\project1> vue init webpack frontend

? Project name todo
? Project description A Vue.js project
? Author bhanuteja.a@tadigital.com
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests Yes
? Pick a test runner jest
? Setup e2e tests with Nightwatch? Yes
? Should we run `npm install` for you after the project has been created? 
(recommended) npm

   vue-cli · Generated "frontend".

Once the setup is done, It’ll show the following commands.

# Project initialization finished!
# ========================

To get started:

  cd frontend
  npm run dev

Documentation can be found at https://vuejs-templates.github.io/webpack

We’ll now get into the folder frontend and type the command as below

npm install //installs all the dependencies mentioned in package.json file
npm run dev //runs frontend and output will be rendered at localhost:8080

Now we have the frontend framework ready, we’ll now move on and create backend using Express.js.

Getting Started with Backend:

Now, go ahead and create a folder named ‘backend‘ inside the ‘project1‘.

Now run the command as below.

PS D:\project1\backend> npm init -y
Wrote to D:\project1\backend\package.json:

{
  "name": "backend",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

Now, go ahead and create src folder inside backend. We’ll create the starting point of backend application main.js file inside the src folder.

Inside main.js, let’s write some script.

console.log('Back-end Executed successfully!');

Now open package.json and add scripts as below.

"scripts": {
    "start": "node src/main.js"
 }

Output will be seen in the console once you run the back-end script.

PS D:\blog\backend> npm start

> backend@1.0.0 start D:\blog\backend
> node src/main.js

Back-end executed Successfully!

Now, let us install dependencies to create express.

Before Express.js Version 4, body-parser need not be installed separately. Now that we’ve to install body-parser extension to make HTTP-post requests.

In order to make HTTP requests, we need some other dependencies as well i.e., body-parser, morgan, cors.

npm i --save express body-parser morgan cors
  • body-parser : body-parser is used to parse JSON, buffer, string or any text submitted using HTTP Post request. req.body have the entire body portion of incoming request received from HTTP Post.
  • morgan : morgan is a middleware used to log requests, errors to the console.
  • cors : Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain.

We’re not going that deep using morgan and cors in this project.

Let us open main.js file, remove console and add the following code.

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const morgan = require('morgan');

const app = express();
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(cors());

app.listen(process.env.PORT || 8081); //backend executes at localhost:8081

Now, lets add some code and test if API is rendering fine or not.

app.get("/todos", (req, res) => {
  res.send([
    {
      Name: "Todo-1",
      Description: "Work with MEVN",
      Status: "Done",
    },
    {
      Name: "Todo-2",
      Description: "Write a blog on MEVN",
      Status: "Done",
    },
    {
      Name: "Todo-3",
      Description: "Get certification in MEVN",
      Status: "Pending",
    },
  ]);
});

Let’s install nodemon. ( nodemon is a utility which monitor for changes in application, when we make any changes and save, it’ll restart the application. )

npm i nodemon --save

Now, make the following changes in package.json.

"scripts": {
    "start": "nodemon src/main.js"
 }

Now, let’s start the application. Output JSON will be rendered at https://localhost:8081/todos

Server restarts automatically whenever you make a change in the back-end application (except the “scripts” changes).

Setting up Middleware:

Now, let us create a connection between backend and frontend using axios.

Axios : axios is used to make HTTP Requests to the backend.

Navigate to frontend folder and run the following command.

npm i axios --save

Now, let’s create a folder named services in frontend/src folder.

Create a file named Api.js inside services and add the following code.

import axios from 'axios'

export default() => {
  return axios.create({
    baseURL: `http://localhost:8081`
  })
}

Now, let’s create another file todos.js in the same location and fetch the todos as mentioned below.

import Api from "@/services/Api";

export default {
  fetchTodoList() {
    return Api().get("todos");
  },
};

Now, Let’s create a new Todos.vue file in src/components to display Todos received from the Api and add the following code.

Todo list

 

export default {
  name: "todos",
  data() {
    return {};
  }
};

Now, remove logo from main component App.vue.

Now, add the new route in src/router/index.js.

import Vue from "vue";
import Router from "vue-router";
import HelloWorld from "@/components/HelloWorld";
import Todos from "@/components/Todos";

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: "/",
      name: "HelloWorld",
      component: HelloWorld,
    },
    {
      path: "/todos",
      name: "Todos",
      component: Todos,
    },
  ],
});

Note: You can remove HelloWorld component and make Todos component in the default path.

When you goto https:localhost:8080/todos, you should be able to see the output as below.

Now, add the below code into Todos.vue component. Here we are receiving the JSON from backend using Api.js

 

Todo list

<template>
  <div>
    <h2 class="todos">Todo list</h2>
    <div class="container">
      <div class="todos--header">
        <div class="flex-item flex-heading item-1">
          <span class="heading">Name</span>
        </div>
        <div class="flex-item flex-heading item-2">
          <span class="heading">Description</span>
        </div>
        <div class="flex-item flex-heading item-3">
          <span class="heading">Status</span>
        </div>
      </div>
      <div class="todos--list" v-for="todo in todos" :key="todo">
        <div class="flex-item item-1">
          <span>{{todo.Name}}</span>
        </div>
        <div class="flex-item item-2">
          <span>{{todo.Description}}</span>
        </div>
        <div class="flex-item item-3">
          <span>{{todo.Status}}</span>
        </div>
      </div>
    </div>
  </div>
</template>
 
<script>
import TodosService from "@/services/todos";
export default {
  name: "todos",
  data() {
    return {
      todos: []
    };
  },
  mounted() {
    this.getTodoList();
  },
  methods: {
    async getTodoList() {
      const response = await TodosService.fetchTodoList();
      console.log(response.data);
      this.todos = response.data;
    }
  }
};
</script>
<style scoped>
.todos {
  text-transform: uppercase;
  font-weight: bold;
}
.todos--header,
.todos--list {
  display: flex;
}
.heading {
  font-weight: bold;
  color: #fff;
}
.flex-item {
  text-align: center;
  margin: 10px;
  border: 1px solid #378eef;
  border-radius: 4px;
  color: #378eef;
  justify-content: center;
  padding: 5px;
}
.item-1 {
  flex-basis: 25%;
}
.item-2 {
  flex-basis: 50%;
}
.item-3 {
  flex-basis: 25%;
}
.flex-heading {
  background: #378eef;
  color: #ccc;
}
</style>

 

When you goto http://localhost:8080/todos, you will see the output as below.

Let us now connect to MongoDB and work on CRUD functionality.

Setting up Mongo:

Let us install mongoose in backend folder by the following command.

npm i mongoose --save

Now, go ahead and add the following code in main.js file inorder to create a connection with mongoose.

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/todos", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error"));
db.once("open", function (callback) {
  console.log("Connection Succeeded");
});

MongoDB Connection is successful, if you are able to see the console log statement as “Connection Succeeded”.

Till here, we have seen how to set up VueJS, Frontend, Backend, Middleware and Mongo.

In the next part, we are going to learn the complete CRUD Functionality.

About The Author