MEVN Stack Tutorial (Beginner) - Building A Basic App

MEVN Stack Tutorial (Beginner) – Building A Basic App

Avatar photoPosted by

What is MEVN stack?

The MEVN stack is a popular web development stack that stands for MongoDB, Express.js, Vue.js, and Node.js. It is a full-stack JavaScript solution used to develop dynamic web applications. Here is a brief overview of each component:

  1. MongoDB: A NoSQL database that stores data in flexible, JSON-like documents. It is highly scalable and ideal for handling large volumes of data.
  2. Express.js: A lightweight web application framework for Node.js that simplifies the process of building robust APIs. It provides a range of features for web and mobile applications.
  3. Vue.js: A progressive JavaScript framework used for building user interfaces. Vue.js is known for its simplicity, flexibility, and ease of integration with other projects and libraries.
  4. Node.js: A JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows developers to execute JavaScript on the server side, making it possible to use JavaScript for both client-side and server-side development.

In a MEVN stack application, the typical workflow involves:

  • Frontend: Vue.js is used to build the client-side interface. It communicates with the backend via HTTP requests.
  • Backend: Node.js with Express.js handles the server-side logic, processes requests, and interacts with the database.
  • Database: MongoDB stores the application data, which can be queried and manipulated using the Mongoose library in Node.js.

This stack enables developers to use JavaScript across the entire development process, from the client-side (frontend) to the server-side (backend) and database management, promoting efficiency and consistency in the development workflow.

Preview:

Backend Development

We will now develop our backend.

Prerequisite:

  • MongoDB
  • Node (This tutorial uses 18.20.2)

File Structure Preview:

image 45 Binaryboxtuts

Step 1:Initialize Node.js project

Create a folder named mean-backend, go into the newly created folder and open your terminal or cmd, and run this command:

npm init -y

Running npm init -y initializes a new Node.js project in the current directory using default values for package.json fields, without requiring user input. The -y flag stands for “yes,” which means it automatically accepts all defaults. This command is useful for quickly setting up a new project without having to manually enter information for each field in the package.json file.

Step 2: Install Packages

After initializing a node.js project, let’s install the packages that we will be using:

npm install express
npm install dotenv
npm install cors
npm install mongoose
  • express – Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web applications and APIs. It is designed to make the process of creating server-side applications in Node.js simpler and more efficient.
  • dotenv – is a popular npm package that loads environment variables from a .env file into process.env, making it easy to manage configuration settings in Node.js applications.
  • cors – CORS (Cross-Origin Resource Sharing) middleware package in a Node.js project. CORS is a security feature implemented by web browsers to prevent unauthorized access to resources hosted on a different origin (domain, protocol, or port) than the one making the request.
  • mongoose – Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js, designed to work in an asynchronous environment. It provides a straightforward schema-based solution to model your application data and handle interactions with a MongoDB database.

Then let’s install the nodemon package, if you have already installed nodemon you can skip this.

  • nodemon – is a utility that monitors changes in your Node.js application files and automatically restarts the server whenever a change is detected. This eliminates the need to manually stop and restart the server every time you make changes to your code, making the development process more efficient and productive. Nodemon is particularly useful during the development phase of a Node.js application when you frequently make changes to your code and want to see the changes reflected immediately without having to restart the server manually.
npm install -g nodemon 

Running npm install -g nodemon installs the Nodemon package globally on your system. The -g flag stands for “global,” which means Nodemon will be installed in a location accessible system-wide, rather than being installed locally in a specific project directory.

Step 3: Setup Express Application

Create a file inside our root folder, name the file server.js, and add these lines of codes:

server.js

require('dotenv').config()

const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const projectRoutes = require('./routes/projectApi')

// express app
const app = express()

// middleware
app.use(express.json())
app.use(cors())
app.use((req, res, next) => {
  console.log(req.path, req.method)
  next()
})

// routes
app.use('/api/projects', projectRoutes)

// connect to mongodb
mongoose.connect(process.env.MONGO_URI)
.then(() => {
    console.log('connected to database')
    // listen to port
    app.listen(process.env.PORT, () => {
        console.log('listening for requests on port', process.env.PORT)
    })
})
.catch((err) => {
    console.log(err)
}) 

In an Express.js application, the entry point is typically the main file where you initialize the Express server and define its configurations, routes, and middleware. This main file is commonly named server.js or app.js, but it can be named anything you prefer.
The entry point file is where you set up your Express application by importing the necessary modules, creating an instance of Express, defining routes, applying middleware, and starting the server. It’s the starting point of your application’s execution.

Step 4: Update package.json

Add this line on the scripts field “dev”: “nodemon server.js”. The scripts field defines a set of commands that can be executed via npm. These scripts provide shortcuts for common development tasks, such as starting the server, running tests, building the project, etc.

package.json

{
  "name": "express-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "mongoose": "^8.3.2"
  }
}

Step 5: Setup Environment Variables

Create a .env file, and add the environment variables.

.env

PORT=4000
MONGO_URI=mongodb://127.0.0.1:27017/express_rest_api
  • PORT – port number on which the server should listen for incoming HTTP requests
  • MONGO_URI – refers to the Uniform Resource Identifier (URI) used to connect to a MongoDB database. It contains information such as the protocol, hostname, port, database name, and optionally authentication credentials.

You can get the url when you open the MongoDBCompass:

image 39 Binaryboxtuts

Sample .env

PORT=4000
MONGO_URI=mongodb://127.0.0.1:27017/express_rest_api

Step 6: Create A Model

Create a folder named models inside our root folder,  and inside it create a file named projectModel.js and add these lines of code.

models\projectModel.js

const mongoose = require('mongoose')

const Schema = mongoose.Schema

const projectSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },

}, { timestamps: true })

module.exports = mongoose.model('project', projectSchema)

Step 7: Create A Controller

Create a folder named controllers inside our root folder,  and inside it create a file named projectController.js and add these lines of code.

controllers\projectController.js

const Project = require('../models/projectModel')
const mongoose = require('mongoose')

// get list of projects
const getProjects = async (req, res) => {
  const projects = await Project.find({}).sort({createdAt: -1})

  res.status(200).json(projects)
}

// create a new project
const createProject = async (req, res) => {
    const {name, description} = req.body
  
    // add to the database
    try {
      const project = await Project.create({ name, description })
      res.status(200).json(project)
    } catch (error) {
      res.status(400).json({ error: error.message })
    }
  }

// get specific project
const getProject = async (req, res) => {
  const { id } = req.params

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(404).json({error: 'No project found for id ' + id})
  }

  const project = await Project.findById(id)

  if (!project) {
    return res.status(404).json({error: 'No project found for id ' + id})
  }

  res.status(200).json(project)
}

// update a project
const updateProject = async (req, res) => {
    const { id } = req.params
    const {name, description} = req.body
    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(404).json({error: 'No project found for id ' + id})
    }

    const project = await Project.findOneAndUpdate({_id: id}, {name, description}, {returnOriginal: false})

    if (!project) {
      return res.status(404).json({error: 'No project found for id ' + id})
    }

    res.status(200).json(project)
}
  
// delete a project
const deleteProject = async (req, res) => {
    const { id } = req.params
  
    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(404).json({error: 'No project found for id ' + id})
    }
  
    const project = await Project.findOneAndDelete({_id: id})
  
    if(!project) {
      return res.status(404).json({error: 'No project found for id ' + id})
    }
  
    res.status(200).json({message: 'Project deleted.'})
  }
  


module.exports = {
  getProjects,
  createProject,
  getProject,
  updateProject,
  deleteProject
}

Step 8: Create A Route

Create a folder named routes inside our root folder, and inside it create a file named projectApi.js and add these lines of code.

routes\projectApi.js

const express = require('express')
const {
    getProjects,
    createProject,
    getProject,
    updateProject,
    deleteProject
} = require('../controllers/projectController')


const router = express.Router()

// get list of projects
router.get('/', getProjects)

// create a new project
router.post('/', createProject)

// get specific project
router.get('/:id', getProject)

// update a project
router.patch('/:id', updateProject)

// delete a project
router.delete('/:id', deleteProject)



module.exports = router

Step 9: Start the Express App

Run this command to start the Express App:

npm run dev

After successfully running your app, the base url of our app will be:

http://localhost:4000

Test the API:

We will be using Insomia for testing our API, but you can use your preferred tool.

POST Request – This request will create a new resource.

image 40 Binaryboxtuts

GET Request – This request will retrieve all the resources.

image 41 Binaryboxtuts

GET Request (with id) – This request will retrieve a particular resource.

image 42 Binaryboxtuts

PATCH Request  – This request will update a resource.

image 43 Binaryboxtuts

DELETE Request – This request will delete a resource.

image 44 Binaryboxtuts

Front End Development

We will now develop our frontend.

Prerequisite:

  • npm
  • node (This tutorial uses 18.20.2)
  • @vue/cli

Step 1: Create A Vue.js Project

First, select a folder that you want the Vue.js project to be created then execute this command on Terminal or CMD :

vue create mevn-frontend

make sure you select vue 3. Refer to the image below:

image 18 Binaryboxtuts

Step 2: Install packages

After creating a fresh vue.js project, go to the vue.js project folder and install these packages:

  • vue-router – a package used for routing and the official router for vue.js
  • bootstrap – a package of bootstrap framework
  • sweetalert2 -a package for pop-up boxes
  • axios – a promised-based HTTP library that is used to request to a server or API.
npm i bootstrap
npm i vue-router
npm i sweetalert2
npm i axios

Step 3: Create .env

After installing the packages, we will create our .env file in our root directory. We will declare the API base URL in the .env file. Don’t forget to add it to the .gitignore file. The VUE_APP_API_URL is the URL of our express app.

.env

VUE_APP_API_URL="http://localhost:4000/"

Step 4: Routing and Components

We will now create the components, refer to the image below for the file structure.

image 17 Binaryboxtuts

You can create your own file structure but for this tutorial just follow along.

Let’s update the main.js file – We will add the axios base URL and add the API Key on the axios header.

src/main.js

import { createApp } from 'vue';
import App from './App.vue';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.css';
import { createRouter, createWebHistory } from 'vue-router';
import ProjectList from './components/pages/ProjectList';
import ProjectCreate from './components/pages/ProjectCreate';
import ProjectEdit from './components/pages/ProjectEdit';
import ProjectShow from './components/pages/ProjectShow';
  
axios.defaults.baseURL = process.env.VUE_APP_API_URL

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: ProjectList },
    { path: '/create', component: ProjectCreate },
    { path: '/edit/:id', component: ProjectEdit },
    { path: '/show/:id', component: ProjectShow },
  ],
});
  
createApp(App).use(router).mount('#app');

Let’s update the App.vue file – Let’s change all the code in it:

src/App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
};
</script>

Let’s create a file named LayoutDiv.vue – this will serve as a template.

src/components/LayoutDiv.vue

<template>
  <div class="container">
    <slot></slot>
  </div>
</template>

<script>

export default {
    name: 'LayoutDiv',
};
</script>

We will now create a directory src/components/pages. Inside the folder let’s create these files for our pages:

  • ProjectCreate.vue
  • ProjectEdit.vue
  • ProjectList.vue
  • ProjectShow.vue

src/components/pages/ProjectCreate.vue

<template>
  <layout-div>
    <h2 class="text-center mt-5 mb-3">Create New Project</h2>
    <div class="card">
        <div class="card-header">
            <router-link 
                class="btn btn-outline-info float-right"
                to="/">View All Projects
            </router-link>
        </div>
        <div class="card-body">
            <form>
                <div class="form-group">
                    <label htmlFor="name">Name</label>
                    <input 
                        v-model="project.name"
                        type="text"
                        class="form-control"
                        id="name"
                        name="name"/>
                </div>
                <div class="form-group">
                    <label htmlFor="description">Description</label>
                    <textarea 
                        v-model="project.description"
                        class="form-control"
                        id="description"
                        rows="3"
                        name="description"></textarea>
                </div>
                <button 
                    @click="handleSave()"
                    :disabled="isSaving"
                    type="button"
                    class="btn btn-outline-primary mt-3">
                    Save Project
                </button>
            </form>
        </div>
    </div>
  </layout-div>
</template>

<script>
import axios from 'axios';
import LayoutDiv from '../LayoutDiv.vue';
import Swal from 'sweetalert2'

export default {
  name: 'ProjectCreate',
  components: {
    LayoutDiv,
  },
  data() {
    return {
      project: {
        name: '',
        description: '',
      },
      isSaving:false,
    };
  },
  methods: {
    handleSave() {
        this.isSaving = true
        axios.post('/api/projects', this.project)
          .then(response => {
            Swal.fire({
                icon: 'success',
                title: 'Project saved successfully!',
                showConfirmButton: false,
                timer: 1500
            })
            this.isSaving = false
            this.project.name = ""
            this.project.description = ""
            return response
          })
          .catch(error => {
            this.isSaving = false
            Swal.fire({
                icon: 'error',
                title: 'An Error Occured!',
                showConfirmButton: false,
                timer: 1500
            })
            return error
          });
    },
  },
};
</script>

src/components/pages/ProjectEdit.vue

<template>
   <layout-div>
        <h2 class="text-center mt-5 mb-3">Edit Project</h2>
        <div class="card">
            <div class="card-header">
                <router-link 
                    class="btn btn-outline-info float-right"
                    to="/">View All Projects
                </router-link>
            </div>
            <div class="card-body">
                <form>
                    <div class="form-group">
                        <label htmlFor="name">Name</label>
                        <input 
                            v-model="project.name"
                            type="text"
                            class="form-control"
                            id="name"
                            name="name"/>
                    </div>
                    <div class="form-group">
                        <label htmlFor="description">Description</label>
                        <textarea 
                            v-model="project.description"
                            class="form-control"
                            id="description"
                            rows="3"
                            name="description"></textarea>
                    </div>
                    <button 
                        @click="handleSave()"
                        :disabled="isSaving"
                        type="button"
                        class="btn btn-outline-primary mt-3">
                        Save Project
                    </button>
                </form>
            </div>
        </div>
   </layout-div>
</template>

<script>
import axios from 'axios';
import LayoutDiv from '../LayoutDiv.vue';
import Swal from 'sweetalert2'

export default {
  name: 'ProjectEdit',
  components: {
    LayoutDiv,
  },
  data() {
    return {
      project: {
        name: '',
        description: '',
      },
      isSaving:false,
    };
  },
  created() {
    const id = this.$route.params.id;
    axios.get(`/api/projects/${id}`)
    .then(response => {
        let projectInfo = response.data
        this.project.name = projectInfo.name
        this.project.description = projectInfo.description
        return response
    })
    .catch(error => {
        Swal.fire({
            icon: 'error',
            title: 'An Error Occured!',
            showConfirmButton: false,
            timer: 1500
        })
        return error
    })
  },
  methods: {
    handleSave() {
        this.isSaving = true
        const id = this.$route.params.id;
        axios.patch(`/api/projects/${id}`, this.project)
          .then(response => {
            Swal.fire({
                icon: 'success',
                title: 'Project updated successfully!',
                showConfirmButton: false,
                timer: 1500
            })
            this.isSaving = false
            this.project.name = ""
            this.project.description = ""
            return response
          })
          .catch(error => {
            this.isSaving = false
            Swal.fire({
                icon: 'error',
                title: 'An Error Occured!',
                showConfirmButton: false,
                timer: 1500
            })
            return error
          });
    },
  },
};
</script>

src/components/pages/ProjectList.vue

<template>
    <layout-div>
          <div class="container">
              <h2 class="text-center mt-5 mb-3">Project Manager</h2>
              <div class="card">
                  <div class="card-header">
                      <router-link to="/create"
                          class="btn btn-outline-primary"
                          >Create New Project
                      </router-link>
                  </div>
                  <div class="card-body">
               
                      <table class="table table-bordered">
                          <thead>
                              <tr>
                                  <th>Name</th>
                                  <th>Description</th>
                                  <th width="240px">Action</th>
                              </tr>
                          </thead>
                          <tbody>
                               
                              <tr v-for="project in projects" :key="project.id">
                                  <td>{{project.name}}</td>
                                  <td>{{project.description}}</td>
                                  <td>
                                      <router-link :to="`/show/${project._id}`" class="btn btn-outline-info mx-1">Show</router-link>
                                      <router-link :to="`/edit/${project._id}`" class="btn btn-outline-success mx-1">Edit</router-link>
                                      <button 
                                          @click="handleDelete(project._id)"
                                          className="btn btn-outline-danger mx-1">
                                          Delete
                                      </button>
                                  </td>
                              </tr>
                                   
                          </tbody>
                      </table>
                  </div>
              </div>
          </div>
      </layout-div>
  </template>
   
  <script>
  import axios from 'axios';
  import LayoutDiv from '../LayoutDiv.vue';
  import Swal from 'sweetalert2'
   
  export default {
    name: 'ProjectList',
    components: {
      LayoutDiv,
    },
    data() {
      return {
        projects:[]
      };
    },
    created() {
      this.fetchProjectList();
    },
    methods: {
      fetchProjectList() {
        axios.get('/api/projects')
          .then(response => {
              this.projects = response.data;
              return response
          })
          .catch(error => {
            return error
          });
      },
      handleDelete(id){
          Swal.fire({
              title: 'Are you sure?',
              text: "You won't be able to revert this!",
              icon: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#3085d6',
              cancelButtonColor: '#d33',
              confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
              if (result.isConfirmed) {
                  axios.delete(`/api/projects/${id}`)
                  .then( response => {
                      Swal.fire({
                          icon: 'success',
                          title: 'Project deleted successfully!',
                          showConfirmButton: false,
                          timer: 1500
                      })
                      this.fetchProjectList();
                      return response
                  })
                  .catch(error => {
                      Swal.fire({
                           icon: 'error',
                          title: 'An Error Occured!',
                          showConfirmButton: false,
                          timer: 1500
                      })
                      return error
                  });
              }
            })
      }
    },
  };
  </script>

src/components/pages/ProjectShow.vue

<template>
   <layout-div>
        <h2 class="text-center mt-5 mb-3">Show Project</h2>
        <div class="card">
            <div class="card-header">
                <router-link 
                    class="btn btn-outline-info float-right"
                    to="/">View All Projects
                </router-link>
            </div>
            <div class="card-body">
                <b className="text-muted">Name:</b>
                <p>{{project.name}}</p>
                <b className="text-muted">Description:</b>
                <p>{{project.description}}</p>
            </div>
        </div>
   </layout-div>
</template>

<script>
import axios from 'axios';
import LayoutDiv from '../LayoutDiv.vue';
import Swal from 'sweetalert2'

export default {
  name: 'ProjectShow',
  components: {
    LayoutDiv,
  },
  data() {
    return {
      project: {
        name: '',
        description: '',
      },
      isSaving:false,
    };
  },
  created() {
    const id = this.$route.params.id;
    axios.get(`/api/projects/${id}`)
    .then(response => {
        let projectInfo = response.data
        this.project.name = projectInfo.name
        this.project.description = projectInfo.description
        return response
    })
    .catch(error => {
        Swal.fire({
            icon: 'error',
            title: 'An Error Occured!',
            showConfirmButton: false,
            timer: 1500
        })
        return error
    })
  },
  methods: {
    
  },
};
</script>

Step 5: Run the app

We’re all done, what is left is to run the app.

npm run serve

Open this URL:

http://localhost:8080/

Screenshots:

Index Page

How To Develop ReactJS CRUD App using a REST API

Create Page

How To Develop ReactJS CRUD App using a REST API

Edit Page

How To Develop ReactJS CRUD App using a REST API

Show Page

How To Develop ReactJS CRUD App using a REST API