Skip to content

Coding 4 Developers

Running Code Website

  • Home
  • Angular2,4,5,6,7,8
  • Node.js
  • LARAVEL
  • PHP
  • XMPP
  • JAVASCRIPT
  • Contact Us
  • Online Test

Tag: login and register in node js

Login, Logout and Register in Node JS & Mongo DB | Session in Node JS

To install the mongoose:                                                                                                                        

mongoose installation
1
npm install mongoose

To install the session:

1
npm install --save express-session

routes/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
var express = require('express');
var router = express.Router();
 
var User = require('../schema/user');
var Response = require('../common/response');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
 
 
/* REGISTER USER. */
router.post('/register', function(req, res) {
var data = new User(req.body);
data.save(function(err){
  if(err){
    console.log(err);
      Response.errorResponse(err.message,res);
  }else{
      Response.successResponse('User registered successfully!',res,{});
  }
})
});
 
 
/* LOGIN USER. */
router.post('/login', function(req, res) {
var email = req.body.email;
var password = req.body.password;
User.findOne({email: email, password: password}, function(err,user){
   if(err){
     console.log(err);
      Response.errorResponse(err.message,res);
   }
   if(!user){
     Response.notFoundResponse('Invalid Email Id or Password!',res);
   }else{
     req.session.user = user;
     Response.successResponse('User loggedin successfully!',res,user);
   }
  
})
});
 
/* GET DASHBOARD */
router.get('/dashboard', function(req, res) {
  if(!req.session.user){
    Response.unauthorizedRequest('You are not logged in',res);
  }else{
    Response.successResponse('Welcome to dashboard!',res,req.session.user);
  }
  
});
 
 
/* GET LOGOUT */
router.get('/logout', function(req, res) {
  req.session.destroy(function(err){  
        if(err){  
            console.log(err);
            Response.errorResponse(err.message,res);
        }  
        else  
        {  
            Response.successResponse('User logged out successfully!',res,{});
        }  
    });
});
 
module.exports = router;

MongoDB connection using mongoose with node JS:

Write the following code in app.js
1
2
3
4
5
6
7
8
9
// DB connection
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/login_register', {
    useMongoClient: true
})
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
// DB connection end
Add route in app.js also:
1
2
3
4
5
6
7
var session = require('express-session');
 
app.use(session({
  secret: 'djhxcvxfgshjfgjhgsjhfgakjeauytsdfy', // a secret key you can write your own
  resave: false,
  saveUninitialized: true
}));

Create schema for blog post: ...  Read More

Share This:


July 30, 2017 Node.js login and register in node js, login user in node js and mongo db, login user with session in node js, session in node js

Categories

  • Ajax (4)
  • Angular2,4,5,6,7,8 (16)
  • ANGULARJS (4)
  • Facebook API (1)
  • FFMPEG (1)
  • Google Maps API (18)
  • JAVASCRIPT (43)
  • JQUERY (29)
  • LARAVEL (25)
  • Mongo DB (10)
  • MySql (9)
  • MySQL Interview Question & Answers (3)
  • Node.js (18)
  • PHP (45)
  • Python (1)
  • React.js (1)
  • Redis (1)
  • Stripe (2)
  • XMPP (14)
  • ZEND FRAMEWORK (8)

Subscribe to Coding 4 Developers

Follow us on Twitter

Recent Posts

  • MongoDB insertMany() document size | How to check maxWriteBatchSize in MongoDB
  • JWT - Why we don't need to store tokens in database?
  • How to use Typescript with Node.js | Building a Node.js App with TypeScript
  • Custom Directives in Angular 8 | Angular Directive Tutorial With Example
  • Difference between find() and filter() in JavaScript | ES6 some() and every() functions example

Information

  • About Coding 4 Developers
  • Contact Us
  • Privacy Policy

Most Visited Categories

  • Angular2,4,5,6,7,8
  • PHP
  • Node.js
  • LARAVEL
  • XMPP

Recent Posts

  • MongoDB insertMany() document size | How to check maxWriteBatchSize in MongoDB
  • JWT - Why we don't need to store tokens in database?
  • How to use Typescript with Node.js | Building a Node.js App with TypeScript

Subscribe

Proudly developed by Saurabh