Node.js implements login verification + Tab (improved version)

Keywords: node.js MySQL JQuery


requirement

Question 1:
Use the express framework of Node.js and JQuery to complete the following requirements:
1. Design a login page. It is required to enter the user name, password and login button on the login page.
2. When clicking the login button, use JQuery's AJAX to post the contents of the form.
3. Use node.js and express to build a web service and respond to the post request in point 2. When the user name is admin and the password is 123, return json data to remind success, otherwise it will fail.
4. After the HTML page gets the json data, if it succeeds, remove the login box and replace it with "Welcome: admin", and there is an exit button. If you exit, the login box will be restored; If the login fails, just remind the user name or password error.

Question 2:
Use the express framework of Node.js and JQuery to complete the following requirements:
1. Design an html page with three tab buttons: "human resources department", "development department" and "logistics support department".
2. Click different buttons to request a route with JQuery's get method, such as: http://localhost/dev
3. Use node.js and express to build a web service, respond to the get request in point 2, and return the json data of the Department personnel. The data is required to be in the MySQL database and queried by the MySQL component of node.
4. After the HTML page gets the json data, build the data under the corresponding button.

Operation results

See ↓ for directory structure

The project needs to install express and mysql modules. The command is npm install express/mysql
jquery download

app.js

node click this file

const express = require('express');
const app = express();
//Introduction routing
const router1 = require('./router/test1'); 
const router2 = require('./router/test2');

app.use(express.static('./public'));//Set public as the static file path
app.use(router1);//Use router1
app.use(router2);//Using router2

app.use('/',function(req,res){
    res.sendFile(__dirname + "/" + "public/index.html");
});

var server = app.listen(8808,function(){
    var port = server.address().port;
    console.log("http://localhost:%s",port);
});

index.html

A useless document is optional.. Just for the convenience of going to different pages

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>welcome</title>
</head>
<body>
    <label>Question 1:</label>
    <a href="http://Localhost: 8808 / test1. HTML "> login</a>
    <br>
    <label>Question 2:</label>
    <a href="http://Localhost: 8808 / test2. HTML "> tab</a>
</body>
</html>

First question

test1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign in</title>
    <script src="./js/jquery-3.6.0.js"></script>
</head>
<body>
    <div id="login-div">
        <div class="info">
            <label>Account:</label>
            <input type="text" name="username" id="user">
        </div>
        <div class="info">
            <label>password:</label>
            <input type="password" name="passwd" id="passwd">
        </div>
        <div class="info">
            <button id="loginBtn">Sign in</button>
        </div>
        <div class="msg">

        </div>
    </div>
    <script>
        //Sign in
        $("#loginBtn").click(function () { 
            $.ajax({
                type:"post",
                url:"/login",
                data:{
                    username:$("#user").val(),
                    password:$("#passwd").val()
                },
                dataType:'JSON',
                complete:function(result){
                    if(result.responseJSON=='success'){
                        $('.info').remove();
                        $('.msg').empty();
                        $('.msg').append('<p>welcome: admin</p>')
                        $('.msg').append('<button id="exit">sign out</button>')
                    }else{
                        $('.msg').empty();
                        $('.msg').append('<p style="color:red">Wrong account or password!</p>')
                    }
                }
            });
        });

        //sign out
        $(document).on('click','#exit',function(){
            window.location.reload();//In fact, it will return to the original login page after refreshing here. The writing is not very good. If you are lazy, you won't change it hhh
        });
    </script>
</body>
</html>

In the actual project development, there are usually dozens or hundreds of routes. If they are written in a js file, it will be very bloated.. express specifically provides a routing function to encapsulate requests.
Each routing file generates an express.Router instance and exports it, and mounts it to different paths through app.use.
In actual development, it is recommended to use express.Router to separate different routes into different route files.
*The above text is taken from Node.js uses the Express.Router method -- script home

router/test1.js

const express = require('express');
const router = express.Router();//Create a routing container
//The parameters submitted in the post mode are of type urlencoded, so we need to resolve them here
router.use(express.urlencoded({extended:true}));

router.post('/login',function(req,res){
    //When the account name is equal to admin and the password is equal to 123
    if(req.body.username=='admin'&& req.body.password=='123'){
        res.json('success');
    }
    else{
        res.json('error')
    }
});

module.exports = router;//Export this container

Second question

test2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>tab </title>
    <link rel="stylesheet" href="./css/test2.css">
    <script src="./js/jquery-3.6.0.js"></script>
</head>

<body>
    <ul id="nav" style="list-style: none; display: flex;">
    </ul>
    <div id="content"></div>

    <script>
    	//Navigation bar content generation
        $.get('/search-dept',function(data){
            for(var i = 0;i < data.length; i++){
                $('#nav').append('<li class="li">'+data[i].dept_name+'</li>');
            }
        });

        //Lic li ck event
        $(document).on('click','li',function(){
            var div = $("<div class='info'></div>");
            var index = $(this).index();//Gets the subscript of the currently clicked li
            $('li').eq(index).addClass('on').siblings().removeClass('on');//li style switching
            //Obtain and display employee information corresponding to different navigation options
            $.get('/search-emp',{id:index+1},function(data){
                $(".info").remove();
                for(var i = 0;i < data.length; i++){
                    var info = $("<div class='info-o'></div>");
                    $(info).append('<h3>full name:'+data[i].pname+'</h3>');
                    $(info).append('<h4>Gender:'+data[i].sex+'</h3>');
                    $(info).append('<h4>Age:'+data[i].age+'</h3>');
                    $(info).append("<hr>");
                    $(div).append(info);
                }
                $("#content").append(div);
            });
        });
    </script>
</body>
</html>

router/test2.js

const express = require('express');
const router = express.Router();
const mysql = require('mysql'); 

//Database connection method
function connDB(){
    conn = mysql.createConnection({
        host:'localhost',
        user:'root',
        password:'4580796', //your password
        database:'test', // your database name
        port:'3306',
    });
    conn.connect(()=>{
        console.log('Database connection is successful!');
    })
}

//Close database method
function closeDB(){
    conn.end(()=>{
        console.log('Successfully closed the database connection!');
    });
}

router.get('/search-dept',function(req,res){
    connDB();
    //Query all department names
    conn.query('select dept_name from department',function(err,data){
        if(err){
            console.log(err);
        }else{
            console.log(data);
            res.json(data);
        }
    });
    closeDB();
});

router.get('/search-emp',function(req,res){
    connDB();
    //Query the employee of the corresponding department according to the Department id
    conn.query('select pname,sex,age from test.employees where dept_id =' + req.query.id, function(err,data){
        if(err){
            console.log(err);
        }else{
            console.log(data);
            res.json(data);
        }
    });
    closeDB();
});

module.exports = router;

test2.css

.li{
    margin-left: 50px;
}

.li:hover{
    cursor: pointer;
}

.on{
    border-bottom: 1px solid black;
}

.info{
    margin: 20px;
}

A rookie. If you have any questions, please point out < @ @ >

Posted by KissMyBrain on Sat, 20 Nov 2021 11:51:09 -0800