Initially involved in the full stack: Node+MySQL implements simple login functions

Initially involved in the full stack: Node+MySQL implements simple login functions

1. Several typical applications of node

  • Automated scaffolding tools : vue-cli, webpack-cli and customized scaffolding tool development.

  • Middle layer : On
    the premise of keeping the front and back ends separated, use node to build a simple Web Server server, which is used to merge the server-side rendering of the page and the data interface.

  • Flexible use of node auxiliary project architecture : for
    example, use node as a cache.

  • Full stack development :
    Use node to make full stacks of small commercial projects and personal blogs.

2. install mysql

Download and install MySQL Server from the mysql official website . After the installation is complete, log in to mysql to see if the mysql connection is successful, as shown in the following figure:

3. realize the simple function of login

1. Create a database and table

create DATABASE user;

use user;

create table userlist(
id int primary key auto_increment,
username char(30) unique,
password char(30)
);
 

2. Insert data into the user table

insert into userlist values(1,'zhangsan','123456');
 

After executing the insert SQL statement, the userlist table has the following data:

3. Install the mysql package in the node project to connect to the database

Use npm in the node project to install the mysql toolkit first:

npm install mysql --save
 

Create server.js and connect to mysql with the mysql package:

const mysql = require('mysql');

// 
const pool = mysql.createPool({
    host: '127.0.0.1',
    port: '3306',
    user: 'root',
    password: 'root123456',
    database: 'user'
})
 

4. Use express framework to realize login function

Client side: create index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> </title>
    <script src="https://cdn.bootcss.com/jquery/2.2.1/jquery.js"></script>
</head>
<body>
    <input type="text" id="username"/>
    <input type="password" id="password"/>
    <button id="login"> </button>
    
    <script type="text/javascript">
    $('#login').click(function(){
        $.ajax({
            type: 'POST',
            url: '/login',
            dataType: 'json',
            data: JSON.stringify({
                username: $('#username').val(),
                password: $('#password').val()
            }),
            success: function (data) {
                if(data.success) {
                    win.loc.href = '/welcome';
                }else{
                    alrt(' ')
                }
            }
        });
    })
    </script>
</body>
</html>
 

server side:

//server.js
const fs = require('fs');
const express = require('express');
const app = express();
const { query } = require('./query-db');

app.get('/', function(req, res) {
    let file = fs.readFileSync('./index.html');
    let _data = file.toString();

    res.setHeader('Content-type','text/html;charset=UTF-8')
    res.send(_data);
})

app.post('/login', function(req, res) {
    let reqData = "";
    res.setHeader('Content-type','text/json;charset=UTF-8')
    req.on('data', function(data){
        reqData += data
    });

    req.on('end', async function(){
        let dataOb = JSON.parse(reqData);
        let word = "select * from userlist where username='";
        word += dataOb.username + "'";
        word += " and password='";
        word += dataOb.password + "'";

        let result = await query(word);
    
        if(result && result.length > 0) {
           // express session express-session
            res.setHeader('Set-Cookie', 'username='+result[0].username)
            res.send(JSON.stringify({
                success: true,
                message: ' '
            }))
        }else{
            res.send(JSON.stringify({
                success: false,
                message: ' '
            }))
        }
        
    })
})

app.get('/welcome', function(req, res) {
    res.send('Login success!')
})

app.listen(3000);
 
//query-db.js
const mysql = require('mysql');
const pool = mysql.createPool({
    host: '127.0.0.1',
    port: '3306',
    user: 'root',
    password: 'root123456',
    database: 'user'
})

let query = function(sql) {
    return new Promise((resolve, reject) => {
        pool.query(sql, function(error, result, fields){
            if (error) throw error;
            resolve(result);
        })
    })
}

module.exports = { query };
 

Login function result chart: