Skip to content

Lishan997/MERN-Project

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 

Repository files navigation

MERN-Project

Creating Webapplication Using MERN Stack

STEPS

1.Object modeling with help of mongoose (category, order, product, user)

2.Mongodb connection and db talk

3.Creating ".env" file and setup environment variables

4.Middeleware and initial routes

1.What is middleware?
Here we are visiting "admin" route and sending response message
const admin = (req, res) => {
    return res.send("<h1>Admin dash board</h1>")
};
app.get("/admin", admin);

If we wanted to do something inbetween requesting and response, thats where middleware come to the picture, isAdmin - Middleware

const admin = (req, res) => {
    return res.send("<h1>Admin dash board</h1>")
};

const isAdmin = (req, res, next) => {
    console.log("isAdmin is running..");
    next();
};

app.get("/admin", isAdmin, admin);
2.Common Middlewares
body-parser --> Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
cookie-parser --> Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
cors --> CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.
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
3.Router in express
First I create authentication route inside the auth.js like below
const express = require('express')
const router = express.Router()

router.get("/signout", (req, res) => {
    res.send("User Signout");
});
module.exports = router;
Inside app.js we use that route with help of below satements 
//import routes (import auth.js file inside routes folder)
const authRoutes = require("./routes/auth");

//routes
app.use("/api", authRoutes);

when we are accessing signout route we have to access it like this way http://localhost:3000/api/signout

4.How to use controller
* Better to create controller file related to route file with same name (auth.js)
* As I understood controllers are the functions definions of routes (inside auth controller)
exports.signout = (req, res) => {
    res.json({
        message: "user signout"
    });
}
* we use above exported function inside auth.js (routes/auth.js) like below
const express = require('express')
const router = express.Router()

const {signout} = require("../controllers/auth");

router.get("/signout", signout);

module.exports = router;
5.Signup
* Create signup router and save data sending throgh postman in to mongodb database

Signup Controller
image

Inside Router
image

6.Validate Request and Show Messages

modified signup route as below with error messages

const express = require('express');
const { check, validationResult } = require('express-validator');
const router = express.Router();

const {signout, signup} = require("../controllers/auth");

router.post(
    "/signup", 
    [
        check("name", "name should be at least 3 charaters").isLength({min : 3}),
        check("email", "email is required").isEmail(),
        check("password", "password should be at least 3 charater").isLength({min : 3})
    ] , 
    signup
);

router.get("/signout", signout);


module.exports = router;

signup controller is modifed like below

const User = require("../models/user");
const { check, validationResult } = require('express-validator');


exports.signup = (req, res) => {


    const errors = validationResult(req);

    if(!errors.isEmpty()){
        return res.status(422).json({
            error: errors.array()[0].msg
        })
    }

    const user = new User(req.body);
    user.save((err, user) => {
        if(err){
            return res.status(400).json({
                err: "Not able to save user in DB "
            })
        }
        res.json({
            name: user.name,
            email: user.email,
            id: user._id
        });
    });
}

See below output of validation message

image

When we use "param" insted of "msg", we can see parametrs that issue has

image

5.Authentication route and token

* signup is a process that we stored users details in to the data base
* How do we make sure that users log in success fully ? obvious thing is take users email or user name and password, and match the password with the data base password, if it is correctly logged in we can return true otherwise return false
* In our user schema we have created authenticate methods that doing same above thing
* How we make sure user is logged in?
1. we either use some kind of cookies
2. we either use some kind of token

using above mechanisam we put some infromation to user's browser to make sure that he has logged in and he can authenticate anypoint of time.
In older apporocah we put cookies based infromation in to the users's browser Now modern application prefer token based methods

  • Create webtoken using "jsonwebtoken", when we are creating webtoke we have to use key and value pair, id:password or email:password
  • After we create webtoken we need to put that token in to User's browser for that we use "cookie-parser"(adding or update things in cookie)
  • How do we continuesly checked in users is authenticated or not, for that we are using "express-jwt"

About

Creating Webapplication Using MERN Stack

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published