这里写自定义目录标题 app.js register.html success.html 初始化项目 mysql
app.js
const express = require("express ");
const bodyParser = require("body-parser");
const mysql = require("mysql ");
const path = require("path");
const app = express ();
// app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 创建与数据库 的连接
const connection = mysql .createConnection({host: 'localhost',user: 'root',password: 'wzbWZB123',database: 'register'
});// 连接到数据库
connection.connect((err) => {if (err) throw err;console.log('连接数据库 成功');
});/*** 注册页面*/
app.get("/", (req, res) => {res.sendFile(path.join(__dirname, "views", "register.html"));
});
app.get("/success", (req, res) => {res.sendFile(path.join(__dirname, "views", "success.html"));
});
/*** 注册接口*/
app.post("/register", (req, res) => { // 用户名,密码,性别,年龄,邮箱地址,注册时间const username = req.body.username;const password = req.body.password;const gender = req.body.gender;const age = req.body.age;const emailaddress = req.body.email;const registertime = new Date();// 创建一个新用户const user = {username, password,gender,age,emailaddress,registertime};// 将新用户插入到数据库 中connection.query('INSERT INTO users SET ?', user, (err, result) => {if(err){if(err.code=="ER_DUP_ENTRY")res.json({success:false,message:"用户名重复"})elseres.json({success:false,message:"未知错误"})}else{res.json({success:true,message:"注册成功"})} });
});
app.listen(8081, ()=> {console.log("http://127.0.0.1:8081");
})
register.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>注册</title><style>body {background-color: #f1f1f1;font-family: Arial, sans-serif;margin: 0;padding: 0;display: flex;justify-content: center;align-items: center;height: 100vh;}.container {max-width: 90%;width: 500px;padding: 20px;background-color: #fff;border-radius: 5px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);box-sizing: border-box;}h2 {text-align: center;margin-bottom: 20px;}.form-group {margin-bottom: 15px;}label {display: block;font-weight: bold;margin-bottom: 5px;}input[type="text"],input[type="password"],select {width: calc(100% - 16px); /* Adjusted to account for padding */padding: 8px;border-radius: 4px;border: 1px solid #ccc;box-sizing: border-box;}button {width: 100%;padding: 10px;background-color: #4CAF50;color: #fff;border: none;border-radius: 4px;cursor: pointer;font-size: 16px;}button:hover {background-color: #45a049;}@media (max-width: 768px) {.container {width: 90%;}}</style>
</head>
<body><div class="container"><h2>用户注册</h2><form id="loginForm"><div class="form-group"><label for="username">用户名:</label><input type="text" id="username" name="username" placeholder="请输入用户名" required></div><div class="form-group"><label for="password">密码:</label><input type="password" id="password" name="password" placeholder="请输入密码" required></div><div class="form-group"><label for="confirm-password">确认密码:</label><input type="password" id="confirm-password" name="confirm_password" placeholder="请输入确认密码" required></div><div class="form-group"><label for="gender">性别:</label><select name="gender" id="gender"><option value="F">女</option><option value="M">男</option></select></div><div class="form-group"><label for="age">年龄:</label><input type="text" id="age" name="age" placeholder="请输入年龄" required></div><div class="form-group"><label for="email">邮箱:</label><input type="text" id="email" name="email" placeholder="请输入邮箱" required></div><div class="form-group"><label for="code">验证码:</label><input type="text" id="code" name="code" placeholder="请输入验证码" required><input type="text" id="verification-code" readonly style="width: 50%;float:left;margin-top:15px;margin-bottom:15px"><button type="button" onclick="createCode()" style="width: 40%;float:right;margin-top:15px;margin-bottom:15px">刷新验证码</button></div><button type="submit">注册</button></form></div><script>// 设置一个全局的变量,便于保存验证码var code;function createCode() {// 首先默认code为空字符串code = '';// 设置长度,这里看需求,我这里设置了6var length = 6;var textValue = document.getElementById('verification-code');// 设置随机字符var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];// 循环length次for (var i = 0; i < length; i++) {// 设置随机数范围, 因为数组的长度是36 所以 Math.random()*36 code += arr[Math.floor(Math.random() * 36)];}// 将拼接好的字符串赋值给展示的ValuetextValue.value = code;}//设置此处的原因是每次进入界面展示一个随机的验证码,不设置则为空window.onload = function (){createCode();}document.getElementById('loginForm').addEventListener('submit', async (e) => {e.preventDefault();const username = document.getElementById('username').value.trim();const password = document.getElementById('password').value.trim();const confirm_password = document.getElementById('confirm-password').value.trim();const gender = document.getElementById("gender").value.trim();const age = document.getElementById("age").value.trim();const email = document.getElementById("email").value.trim();const verification_code = document.getElementById("code").value.trim();// 验证码校验if (verification_code != code) {alert("验证码错误!");return;}// 表单校验if (!username || !password || !gender || !age || !email) {alert('所有内容都不能为空!');return;}// 两次密码校验if (password != confirm_password) {alert("两次密码输入不一致!");return;}// 邮箱校验if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)) {alert('邮箱格式不正确!');return;}// 用户名、密码长度校验if (username.length > 20 || password.length > 20) {alert('用户名和密码长度不能超过 20 个字符!');return;}// 发送请求const response = await fetch('/register', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ username, password, gender, age, email })});const result = await response.json();if (result.success) {window.location.href = 'success';} else {alert(result.message);}});</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>Document</title>
</head>
<body>注册成功
</body>
</html>
初始化项目
npm init -y
npm install express
npm install mysql
/*
Navicat MySQL Data TransferSource Server : localhost
Source Server Version : 80040
Source Host : localhost:3306
Source Database : registerTarget Server Type : MYSQL
Target Server Version : 80040
File Encoding : 65001Date: 2024-12-20 09:27:20
*/SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (`UserID` int NOT NULL AUTO_INCREMENT,`UserName` varchar(50) NOT NULL,`Password` varchar(100) NOT NULL,`Gender` char(1) DEFAULT NULL,`Age` int NOT NULL,`EmailAddress` varchar(255) NOT NULL,`RegisterTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,PRIMARY KEY (`UserID`),UNIQUE KEY `UserName` (`UserName`),CONSTRAINT `users_chk_1` CHECK ((`Gender` in (_utf8mb3'F',_utf8mb3'M'))),CONSTRAINT `users_chk_2` CHECK (((`Age` > 0) and (`Age` <= 150))),CONSTRAINT `users_chk_3` CHECK (regexp_like(`EmailAddress`,_utf8mb3'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}$'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;-- ----------------------------
-- Records of users
-- ----------------------------