what is a mern stack application?

Hey there today we are featuring the mern stack application

Probably you might have come across the word but you have no idea of what it means

Don’t worry today you’ll eventually get to know its meaning and use

Lets start

MERN

MERN stack is a JavaScript stack that is used for building fullstack applications

It comprises of four technologies namely

  • MongoDb
  • Express
  • React
  • NodeJS

Breaking them down into their functionalities

MongoDb is used as our default database

React is used as our front end library

Node and Express is used as our back-end server language

By definition

MongoDb

Is a noSQL database that stores data in form of documents that allows users to create databases,schemas and tables

ReactJS

Is a JavaScript library that allows the development of user interfaces for websites applications

NodeJS

Is an open source JavaScript runtime environment that allows users to run code on server

Express

Is a nodeJS framework that makes the writing of nodeJS simpler and easier

The MERN stack applications is used t o build websites such as social media applications ,ecommerce and ticket reservation systems.

Practical

Having known what mern stack is lets now build a very simple mern stack application that uses the POST and GET request

PREREQUISITES

NodeJS

Postman

Atlas MongoDB

Command line

Make sure you install nodeJS in your local machine from their website here

Follow this guide to set up MongoDB

Follow the command line guide to start on the command line

Finally follow this guide to create your api and install postman

Lets divide this session into two parts

  1. API
  2. Frontend

API

Now let start by creating our API

Create a folder in your computer and name it MERN

Inside the folder create another folder name it api

now open the api folder using the command line

In my case i have

ian@IanoTech:~/Documents/REACT/MERN/api$ 

In the same directory lets initialize our node project by typing

npm init -y

open the project using your suitable text editor

A package.json file will be generated containing the following

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

Modules Set Up

Lets now install some dependencies that we are going to use in our project

1) Express – NodeJS framework that provide server-side logic

npm i express

2)Mongoose – is an Object Data Modeling (ODM) library for MongoDB and Node

npm i mongoose

3)Body-Parser – since we are going to use a post in order to post data we have to use body-parser

npm i body parser

4) cors – Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources

npm i cors

5)Nodemone – is a utility that will monitor for any changes in your source and automatically restart your server

npm i nodemone

On our root directory lets make a server.js file, then lets create our server, Our app is going to run on port 8000, add the following codes

const express = require('express')
const app = express()

const port = 8000;
app.listen(port, ()=> console.log(`listening on ${port}`))

then in the package.json file change it to look like this

{
  "name": "api",
  "version": "1.0.0",
  "description": "",
  "start": "nodemon server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.0",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "mongoose": "^6.3.6",
    "nodemon": "^2.0.16"
  }
}

Importing the modules in our server.s file we have

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


const corsOptions ={
   origin:'*', 
   credentials:true,            //access-control-allow-credentials:true
   optionSuccessStatus:200,
}

app.use(cors(corsOptions));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

const port = 8000;
app.listen(port, ()=> console.log(`app running on ${port}`))

Now lets create our api functionality

In the functionality we will need to connect our database and then write our routes

First lets create some folder and files namely

routes, models and db

in your command line type the following to create the folders and files

ian@IanoTech:~/Documents/REACT/MERN/api$ mkdir db // database folder
ian@IanoTech:~/Documents/REACT/MERN/api$ mkdir routes //routes folder
ian@IanoTech:~/Documents/REACT/MERN/api$ mkdir models // models folder

//files
ian@IanoTech:~/Documents/REACT/MERN/api$ touch db/db.js //database file
<meta http-equiv="content-type" content="text/html; charset=utf-8">ian@IanoTech:~/Documents/REACT/MERN/api$ touch models/User.js //model file
<meta http-equiv="content-type" content="text/html; charset=utf-8">ian@IanoTech:~/Documents/REACT/MERN/api$ touch routes/user.js //route file

to start your server type the following on the command line

npm start

Upon successful completion the following messages will be displayed on the terminal / command line , listening on 8000 so we wont be refreshing every time we make a change on our code since nodemon has everything for us The next step is to connect our database.

To connect lets create a db.js file on our root folder and then add the following codes

DataBase set up

const mongoose = require("mongoose");

mongoose.connect(
    "mongodb+srv://ian_test:<password>@ian.qfm7u.mongodb.net/Fistdatabase?retryWrites=true&w=majority", 
    { useNewUrlParser: true, useUnifiedTopology: true,useCreateIndex: true  }
)
 .then(console.log('connected succesfully'))
 .catch(err=> console.log(err))

Make sure you change your password and the First database to your correct default values used while setting up MongoDB in the cloud from the article above then lets import it in our server.js file and see what happens at the console type the following

require('./db.js')

upon success the console should display the messages below

connected succesfully
listening on 8000

Models

Now lets define our models,this is a definition of how our data is going to look like in other words the type and the fields we are going to have.

In this form we are going to have the name and email fields add the following code to the models/User.js file

const mongoose = require('mongoose')

const personSchema = new mongoose.Schema({
	name :{

		type: String,
		required: true

	},
	
	email: {
		type : String,
		required: true
	}
})

module.exports = mongoose.model('User' , personSchema)

Routes

Lets set up our route functionality by adding the codes below in our routes/user.js

const express = require('express')
const router = express.Router()
const User = require('../models/User')

router.get('/users',async (req,res)=>{
	try{

		const person = await User.find({})
		res.send(person)
	} catch(err){
		res.status(500).send(err) }

	})
// ADD user
router.post('/users', async function (req, res) {

    let user = new User();
    user.name = req.body.name;
    user.email = req.body.email;

   await user.save(function(err){
        if(err){
            console.log(err);
            res.json({msg: "failed"})
        }
        else{
            res.json({msg: "success"})
        }
    });
});



module.exports = router

Then lets import our route and databases files in the server.js file

we will have the following in our server.js

const express = require('express')
const app = express()
const cors = require('cors');
const bodyParser = require('body-parser');
const userRoute = require('./routes/user')

require('./db/db')

const corsOptions ={
   origin:'*', 
   credentials:true,            //access-control-allow-credentials:true
   optionSuccessStatus:200,
}

app.use(cors(corsOptions));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));




app.use('/', userRoute)

const port = 8000;
app.listen(port, ()=> console.log(`app running on ${port}`))

We are done writing our api with the POST and GET functionalities.

Now as we get to part two you can test your api using postman try adding some data and retrieving the data

Guide to using postman

see you in the next part here

Posted in
programming

Post a comment

Your email address will not be published.

As the top software development company in Kenya, we can't wait to show you what we can do. Our team of talented designers and developers are passionate about creating beautiful, functional websites that not only look great, but also help your business grow.
0

No products in the cart.

× Get Help?