Wednesday, October 7, 2020

Login Page with express MySQL and nodeJS code

NodeJS , Express and MySQL login page



<!DOCTYPE html>

<html>

<head><title>NodeJS and SQL Login Form</title>

  <link rel="stylesheet" href="style.css">

  </head>

<body>

  

  <div class="login-form">

  <h1>NodeJS and SQL login form</h1>

    <form action="auth" and method ="post">

    <input type="text" name="username" placeholder="required">

      <input type="password" name="password" placeholder="required">

      <input type="submit">

      

   </form>


  

  </div>

 

  </body>

  <script src="Node.js">

    

//include the packages you want to use by creating a variable

    var mysql= require('mysql');

    var express=require('express');

    var session = require('express-session');

    var bodyParser= require('body-parser');

    var path = require('path');

    

    //then connect with the database by creating another variable

    

    var connection = mysql.createConnection({

     host : 'localhost',

     user : 'root',

     database : 'nodelogin',

      password : ''

      

      

    });

    

    

    //Now its time to use express to handle the sessions and http requests

  var app= express();

  

    //its time to use SESSION and BODYPARSER express packages of express

    //the session package will determine if the user is logged in or not

app.use(session({

  secret : 'secret',

  resave: true,

  saveUninitialized: true

  

  

})) ;   

    

    //now use bodyparser package

    //the bodyparser package will extract the data from the login form and then it will parse into json

app.use(bodyParser.urlencoded({extended:true}));

    app.use(bodyParser.json());

         

   

 //make get request:  to request data from a specified source

    //ALERT: Dont use get method while dealing with sensitive data

    //get requests have length restrictions

    //get method can be bookmarked, cannot modify data, remain in browser history

    //sendFile funtion/method of express is used to send static files to the client

    //beginners can try response.sendFile('log.html')

    app.get('/', function(request, repsonse)

           { repsonse.sendFile(path.join(__dirname + 'log.hmtl'));

      

      

    });

        

    


app.post('/auth', function(request, response) {

var username = request.body.username;

var password = request.body.password;

if (username && password) {

connection.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {

if (results.length > 0) {

request.session.loggedin = true;

request.session.username = username;

response.redirect('/home');

} else {

response.send('Incorrect Username and/or Password!');

}

response.end();

});

} else {

response.send('Please enter Username and Password!');

response.end();

}

});

    

    

    

    

    //make post reqest: to send data to the server to create / update a resource

    //post req have no restrictions on data length

    

    //The data sent to the sever with POST is stored in the request body of HTTP  request

    

    //when the user enters his details, the details are sent to the node server and then our script 

    // will check if such person exists in our database

    

    

    app.post('/auth', function(request, response){

      var username= request.body.username;

      var password= request.body.password;

      if ( username && password) {

        connection.query('SELECT * FROM users WHERE username=? AND password=?',[username,password],

                         function(error, results, fields){

          if (results.length >0){

            request.session.loggedin= true,

              request.session.username= username,

              response.redirect= ('/home')

          } else {

            response.send('please enter username and password');

            response.end();} }

                        

                        

                        )}

      

  

    });



 

    //get request to redirect the user to the home page

    app.get('/', function(request, response){

    if (request.sesion.loggedin){

      response.send('Welcome back,'  + request.session.username + '!');

      

    }  

      response.end();

    }  );

    

    

    //Our web application needs to listen on a port, for testing purposes we'll use port 3000:

    app.listen(3000);

    

    

  

  

  

  </script>

  

</html>

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home