preface
Preparation before starting:
- 1, install mysql; Write a code for the login and registration page.
- Create your own database (myFirst) and table (user);
- 3. Encapsulate the SQL statement operation module;
- 4. Install express module;
Knowledge reserves
- 1. Node is modular
- 2. Database connection pooling and encapsulation
- 3. How callback functions work
- 4. Expres module
Requirements and Principles
landing
We’re going to implement the user to enter a username and password in the input box, and then we’re going to match the user’s input to the information in our database and if it’s there it’s a login success or it’s a login failure. (Note: we are not making regular judgments about the content in the input box.)
registered
The user input the account and password, we will submit the account and password entered by the user to save to our database, save the successful registration is successful, otherwise it is failure. (Note: we are not making regular judgments about the content in the input box.)
The principle of
- 1. To obtain the operation of the database, we need to download the data module in Node, and then encapsulate the operation of the database SQL statement, which is convenient for our subsequent use.
- 2. We also need to create a service. The data submitted by the form is checked against our database through the service’s request and feedback.
- We use the Express module to create the service (instead of using the built-in HTTP module of Node.js).
Database whitelist
Note: when we register successfully, a data entry will be added to the table
Encapsulate SQL statement operations
const mysql = require("mysql");
/ / the connection pool
const pool = mysql.createPool({
host:"localhost".user:"root".// The account name of my local database
password:"123456".// My local database login password
database:"myfirst".// The name of the database I created myself
/ / is optional
queueLimit:3.connectionLimit:20
})
// Add a query method
let query = function(sql,callBack){
pool.getConnection((err,conn) = >{
if (err) {
console.log(err);
return
}
conn.query(sql,(err,data) = >{
if (err) {
console.log(err);
return
}
if(callBack) { callBack(data); }})})}/** * Insert data *@param {*} Table table name *@param {*} Datas data object *@param {*} CallBack callBack function */ after successful insertion
let insert = (table,datas,callBack) = >{
/ / stitching SQL
let fields = ' ';/ / field
let values = ' ';/ / value
for (const k in datas) {
fields += k+"," // Concatenate fields
values += ` '${datas[k]}', `
}
// Clear the last comma.
fields = fields.slice(0, -1);
values = values.slice(0, -1);
// console.log(fields);
// console.log(values);
let sql = `INSERT INTO ${table} (${fields}) VALUES (${values}) `;
query(sql,callBack)
};
// Encapsulate a delete SQL method
let del = (table,datas,callBack) = >{
let arr = ['1 = 1']; // Avoid exception error when datas is empty.
for (const k in datas) {
arr.push(`${k} = '${datas[k]}'`);
}
let sql = `delete from ${table} where ${arr.join(" and ")}`;
query(sql,callBack)
}
/** * Modify method *@param {string} Table table name *@param {object} Sets Indicates the field and value *@param {object} Wheres' judgment condition *@param {Function} CallBack function */
let update = (table,sets,wheres,callBack) = >{
// Prepare an array to concatenate the WHERE clause
let whereArr = ['1 = 1']; // Avoid exception error when datas is empty.
for (const k in wheres) {
whereArr.push(`${k} = '${wheres[k]}'`);
}
// Prepare an array to concatenate the set clause
let setArr = [];
for (const k in sets) {
setArr.push(`${k} = '${sets[k]}'`)}let sql = `UPDATE ${table} SET ${setArr.join(",")} WHERE ${whereArr.join(" and ")}`
query(sql,callBack)
}
/ / export
module.exports = {
query,
insert,
del,
update
};
Copy the code
Note: How to initialize mysql and how to download mysql and how to operate mysql
Create a service
app.js
file
const express = require('express')
// Create a service
const app = express()
const port = 3001
// Import the routing module
app.use(require("./login"));
// This is the server port number
app.listen(port, () = > console.log(`Example app listening on port ${port}! `))
Copy the code
Data acquisition and processing
The login. Js file
const express = require('express')
// Introduce encapsulated SQL statement manipulation module
const db = require('./db')
// Call the express.rotuer () method to create a routing object
const login = express.Router();
// The post parameter is parsed. Write it before the route
login.use(express.urlencoded({ extended: false }));
// Mount the specific route on the route object.
/ / login
login.post('/login'.(req, res) = > {
let { username, pwd } = req.body;
// Call the encapsulated query to check whether the data is identical. If the data is identical, the callback data returns a non-empty array
db.query(`select * from user where name = '${username}' and pwd = '${pwd}'`.(data) = > {
if (data.length > 0) {
res.send('Login successful')}else {
res.send('Login failed')}})})/ / register
login.post('/register'.(req, res) = > {
// Destruct the assignment
let { username:name, pwd:pwd } = req.body;
db.insert('user', { name,pwd }, (data) = > {
if (data.affectedRows > 0) {
res.send("Registration successful!")}else {
res.send("Registration failed!")}})})// Export the routing object with module.exprots
module.exports = login;
Copy the code
HTML part
<! -- login -- style yourself!! -->
<form action="http://127.0.0.1:3001/login" method="post">User name:<input type="text" name="username"><br>Password:<input type="password" name="pwd"><br>
<input type="submit" value="Login" id="btn">
</form>
<! -- Registration -- style your own!! -->
<form action="http://127.0.0.1:3001/register" method="post">User name:<input type="text" name="username"><br>Password:<input type="password" name="pwd"><br>
<input type="submit" value="Registered" id="btn">
</form>
Copy the code