Node.js realizes front and rear end exchange - user login

Keywords: node.js

I recently learned a little about the back-end of Node.js, so as a student of the front-end direction, I began to understand the back-end. I didn't say much and began to introduce it. First of all, if you want to better understand this blog, you need to have a basic knowledge of html, css, javascript and Node.js, as well as a little knowledge of SQL database. Next, let's start this small project.

1, Project requirements

The user is required to enter the login interface. After entering the user name and password, the back end obtains the form information entered by the user. If it is correct, it will jump to the login success page.

ps: the notes are written in detail. Please read the notes more if you don't understand. Of course, I also welcome you to leave a message, but this is not a quick way to solve the problem.

2, Start code

1. Create front-end page (CSS style is omitted here)

<form method="post" action="http://localhost:8080/">
                <input type="text" required="required" id="use_name" placeholder="enter one user name" name="user_name">
                <input type="password" required="required" id="pwd" placeholder="Please input a password" name="user_pwd">
            <button type="submit" class="but">land</button>
</form>

Create the form, use the post submission method, and the submission address is my own host, because I do the local test environment.

Login success page success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login success page</title>
    <style>
        /*Style of success page*/
        .success {
            text-align: center;
            color: #3e8e41;
        }
    </style>
</head>
<body>
<h1 class="success">congratulations! Login succeeded!</h1>
<img src="img/keyboard_coffee.jpg">
</body>
</html>

 

2. The Node.js backend obtains user input data

(1) to introduce the module, you need to install the Node.js environment on your computer. Please install it yourself.

// introduce http modular
const http = require('http');
//Import processing request parameter module
const queryString = require('querystring');
const fs = require('fs');
//Introduction of third parties mime modular
const mime = require('mime');
const path = require("path");

(2) Get user input data

//establishsever Web server object
let sever = http.createServer();
//Bind request events for server objects,Triggered when the client has a request
sever.on('request', function (request, response) {
    /* POST Parameters are received as events
    * data  Event triggered when a request parameter is passed
    * end   The end event is triggered when the parameter transfer is completed
    */
    let postParams = '';  //Define an empty string to receive post parameter
//binding data Trigger event
    request.on('data', function (params) {
        postParams = postParams + params;     //Splicing post parameter
    });
//binding data Trigger event
    request.on('end', function () {
        // hold postParams String processing as object,use querystring In the module parse()method
        // console.log(queryString.parse(postParams));
        //Get specific values, such as user name. Note: user here_ The name must be consistent with the name="user_name" in the front-end HTML code.
        let username = queryString.parse(postParams).user_name;
        let userpwd = queryString.parse(postParams).user_pwd;
}

So far, we have obtained the data entered by the user and stored it in the variables username and userpwd defined by us for the following comparison with the user name and user password obtained from the database.

(3) Get user information from SQL database (I use MySQL database. The database management software I use is DBeaver, because it is free ha ha)

Take a look at the data table in the database I prepared in advance. The database name is test (which can be seen in the configuration item encapsulated in the database later), and the data table name is userinfo

// Database query instance. I'm based on my user name username Query in the database.
//Call the custom encapsulated linked database module
const connection = require("./mysql.js");
connection.query("select * from userinfo where userName=?", [username], function (result, filed) {
            //result yes mysql The original data returned by the query. In query statements'?'Is a placeholder for placing SQL Replace query statement with'[]'The value in.
            //handle mysql Similar returned json Formatted array,Processing as json data
            let resultJson = JSON.stringify(result);
            //JSON.parse()Used to parse JSON character string
            let dataJson = JSON.parse(resultJson);
            //Obtain the specific value after analysis
            let name = dataJson[0].userName;
            let pwd = dataJson[0].userPwd;
      //Compare whether the user information obtained from the database is consistent with the user form input. If it is consistent, jump to the success page, findPage()Page jump function for custom
            if (pwd === userpwd && name === username) {
                console.log("The password is correct!");
                findPage('/success.html', response);
            } else {
                console.log("Wrong password!");
                response.end('<h1>Wrong password!</h1>')
            }
        });
/**
 * Functions that access local static resources
 */
function findPage(url, res) {
    // static Is the absolute path of the spliced static resource
    const static = path.join(__dirname, url);
    // Read local files asynchronously
    //Get the type of file, using mime Modular getType()method
    let fileType = mime.getType(static)   //Get the type of file, using mime Modular getType()method
    //read file
    fs.readFile(static, function (err, result) {
        if (!err) {
            res.end(result);
        }
        
    });
}

(4) Database module encapsulation

Because if I write a pile of code for database linking and other operations every time, the opportunity is very redundant, so I refer to the codes of other bloggers to encapsulate the database linking operation into two files

Database configuration encapsulation file mysql.config.js

//Configure linked database parameters
module.exports = {
    host: 'localhost',
    port: 3306,//Port number
    database: 'test',//Database name
    user: 'root',//Database user name
    password: '123456'//Database password
};

Database link encapsulation file   mysql.js

let mysql = require('mysql');//introduce mysql modular
let databaseConfig = require('./mysql.config');  //Introduce the data in the database configuration module
//Outward exposure method
module.exports = {
    query: function (sql, params, callback) {
        //You need to create a link every time you use it. Close the connection after the data operation is completed
        let connection = mysql.createConnection(databaseConfig);
        connection.connect(function (err) {
            if (err) {
                console.log('Database link failed');
                throw err;
            }
            //Start data operation
            //Pass in three parameters, the first parameter sql Statement, second argument sql The third parameter is the callback function
            connection.query(sql, params, function (err, results, fields) {
                if (err) {
                    console.log('Data operation failed');
                    throw err;
                }
                //Return the queried data to the callback function
                callback && callback(results, fields);
                //results As a result of data operation, fields Some fields as database connections
                //To stop linking the database, you must query the statement again. Otherwise, as soon as you call this method, you will directly stop linking and the data operation will fail
                connection.end(function (err) {
                    if (err) {
                        console.log('Failed to close database connection!');
                        throw err;
                    }
                });
            });
        });
    }
};
The above two files have been in the database query instance const connection = require("./mysql.js"); Called.

So far, we have completed the function of using node.js to query MySQL database and realize user login

I would like to thank the blogger who taught me how to package database operation. His article link is here (11 messages) Node connects to MySQL and encapsulates its addition, deletion, modification and query_ Will my blog - CSDN blog

https://blog.csdn.net/qq_31754523/article/details/99172420

  

 

Posted by rlalande on Sun, 21 Nov 2021 21:24:37 -0800