Xây dựng page login đơn giản với Nodejs Express và MySQL
Lượt xem: 13067
Chào các bạn, ở bài trước dandev cùng các bạn tìm hiểu về cách kết nối mysql trong nodejs. Ở bài này dandev sẽ cùng các bạn xây dựng page login đơn giản với Nodejs sử dụng module express và mysql.
Trước tiên chúng ta cần cài dặt thêm các package sau:
Express: npm install express --save
Express session: npm install express-session --save
Mysql for Nodejs (Bài trước dandev cùng các bạn đã cài đặt) : npm install mysql --save
1. Thêm Style cho form login với css
Các bạn bổ sung thêm file style.css trong static/style.css với nội dung sau:
* {
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "segoe ui", roboto, oxygen, ubuntu, cantarell, "fira sans", "droid sans", "helvetica neue", Arial, sans-serif;
font-size: 16px;
}
body {
background-color: #435165;
}
.login {
width: 400px;
background-color: #ffffff;
box-shadow: 0 0 9px 0 rgba(0, 0, 0, 0.3);
margin: 100px auto;
}
.login h1 {
text-align: center;
color: #5b6574;
font-size: 24px;
padding: 20px 0 20px 0;
border-bottom: 1px solid #dee0e4;
}
.login form {
display: flex;
flex-wrap: wrap;
justify-content: center;
padding-top: 20px;
}
.login form label {
display: flex;
justify-content: center;
align-items: center;
width: 50px;
height: 50px;
background-color: #3274d6;
color: #ffffff;
}
.login form input[type="password"], .login form input[type="text"] {
width: 310px;
height: 50px;
border: 1px solid #dee0e4;
margin-bottom: 20px;
padding: 0 15px;
}
.login form input[type="submit"] {
width: 100%;
padding: 15px;
margin-top: 20px;
background-color: #3274d6;
border: 0;
cursor: pointer;
font-weight: bold;
color: #ffffff;
transition: background-color 0.2s;
}
.login form input[type="submit"]:hover {
background-color: #2868c7;
transition: background-color 0.2s;
}
2. Tạo template login với html
Chúng ta bổ sung thêm file login.html với nội dung sau:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1">
<title>Login</title>
<!-- the form awesome library is used to add icons to our form -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
<!-- include the stylesheet file -->
<link href="/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="login">
<h1>Login</h1>
<form action="/auth" method="post">
<label for="username">
<!-- font awesome icon -->
<i class="fas fa-user"></i>
</label>
<input type="text" name="username" placeholder="Username" id="username" required>
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="password" placeholder="Password" id="password" required>
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
3. Tạo file login.js với nodejs
Các bạn tạo file login.js với nội dung sau
const mysql = require('mysql');
const express = require('express');
const session = require('express-session');
const path = require('path');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodelogin'
});
const app = express();
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));
// http://localhost:3000/
app.get('/', function(request, response) {
// Render login template
response.sendFile(path.join(__dirname + '/login.html'));
});
// http://localhost:3000/auth
app.post('/auth', function(request, response) {
// Capture the input fields
let username = request.body.username;
let password = request.body.password;
// Ensure the input fields exists and are not empty
if (username && password) {
// Execute SQL query that'll select the account from the database based on the specified username and password
connection.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {
// If there is an issue with the query, output the error
if (error) throw error;
// If the account exists
if (results.length > 0) {
// Authenticate the user
request.session.loggedin = true;
request.session.username = username;
// Redirect to home page
response.redirect('/home');
} else {
response.send('Incorrect Username and/or Password!');
}
response.end();
});
} else {
response.send('Please enter Username and Password!');
response.end();
}
});
// http://localhost:3000/home
app.get('/home', function(request, response) {
// If the user is loggedin
if (request.session.loggedin) {
// Output username
response.send('Welcome back, ' + request.session.username + '!');
} else {
// Not logged in
response.send('Please login to view this page!');
}
response.end();
});
app.listen(3000);
4. Script tạo database
CREATE DATABASE IF NOT EXISTS `nodelogin` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `nodelogin`;
CREATE TABLE IF NOT EXISTS `accounts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `accounts` (`id`, `username`, `password`, `email`) VALUES (1, 'test', 'test', 'test@test.com');
Video thao tác cùng dandev (phần cuối ở video dandev chia sẻ thêm không có sẵn trên blog nhé)