SQL 代码:
CREATE DATABASE login_exam;
USE login_exam;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(20) NOT NULL UNIQUE,
password VARCHAR(20) NOT NULL
);
-- 插入测试数据
INSERT INTO users (username, password) VALUES
('zhangsan', 123456),
('lisi', '123456');
前端代码:login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录页面</title>
</head>
<body>
<h2>用户登录</h2>
<form id="loginForm">
<label for="username">用户名:</label>
<input type="text" id="username" maxlength="20">
<br><br>
<label for="password">密码:</label>
<input type="password" id="password" maxlength="20">
<br><br>
<button type="button" id="clearButton">清空</button>
<button type="submit" id="loginButton">登录</button>
</form>
<script>
document.getElementById('clearButton').addEventListener('click', () => {
document.getElementById('username').value = '';
document.getElementById('password').value = '';
alert('内容已清空');
});
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
if (!username || !password) {
alert('用户名和密码不能为空!');
return;
}
if (username.length > 20 || password.length > 20) {
alert('用户名和密码长度不能超过 20 个字符!');
return;
}
const response = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const result = await response.json();
if (result.success) {
window.location.href = '/success.html?timestamp=' + Date.now();
} else {
alert('用户名或者密码不正确');
}
});
</script>
</body>
</html>
前端代码:success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录成功</title>
</head>
<body>
<h2>登录成功</h2>
<p>当前时间戳:<span id="timestamp"></span></p>
<script>
const urlParams = new URLSearchParams(window.location.search);
const timestamp = urlParams.get('timestamp');
document.getElementById('timestamp').textContent = timestamp ? new
Date(parseInt(timestamp)).toString() : '未知';
</script>
</body>
</html>
后端代码(node.js 实现)
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const app = express();
app.use(bodyParser.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'login_exam'
});
app.post('/login', (req, res) => {
const { username, password } = req.body;
db.query('SELECT * FROM users WHERE username = ? AND password = ?', [username,
password], (err, results) => {
if (err) {
return res.status(500).json({ success: false, message: '服务器错误' });
}
if (results.length > 0) {
res.json({ success: true });
} else {
res.json({ success: false, message: '用户名或者密码不正确' });
}
});
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});