express+mysql实现注册功能

server/2024/12/23 21:17:34/

这里写自定义目录标题

  • 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

mysql_280">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
-- ----------------------------

http://www.ppmy.cn/server/152584.html

相关文章

React源码02 - 基础知识 React API 一览

1. JSX到JavaScript的转换 <div id"div" key"key"><span>1</span><span>2</span> </div>React.createElement("div", // 大写开头会当做原生dom标签的字符串&#xff0c;而组件使用大写开头时&#xff0c;这…

go面试问题

1 Go的内存逃逸如何分析 go build -gcflags-m main_pointer.go 2 http状态码 300 请求的资源可包括多个位置&#xff0c;相应可返回一个资源特征与地址的列表用于用户终端&#xff08;例如&#xff1a;浏览器&#xff09;选择 301 永久移动。请求的资源已被永久的移动到新U…

LLaMA-Factory 单卡3080*2 deepspeed zero3 微调Qwen2.5-7B-Instruct

环境安装 git clone https://gitcode.com/gh_mirrors/ll/LLaMA-Factory.gitcd LLaMA-Factorypip install -e ".[torch,metrics]"pip install deepspeed 下载模型 pip install modelscope modelscope download --model Qwen/Qwen2.5-7B-Instruct --local_dir /roo…

中国工程科技2040发展战略研究

近日&#xff0c;中国工程院“中国工程科技未来20年发展战略研究”总体项目组发布《愿景驱动的中国工程科技2040发展战略研究》&#xff0c;基于我国工程科技发展需求和世界发展趋势&#xff0c;提出“经济预测-需求分析-技术预见-愿景分析-战略架构-技术路线图-政策选择”战略…

uniapp 微信小程序 均分数据展示

效果图 数据展示&#xff0c;可自行搭配 html <view class"num-wrapper"><view class"num-item" click.stop"routerGo(跳转的地址)"><text class"num">&#xffe5;{{ 要展示的数据 || 0}}</text><view…

windows11 环境 paddleOCR 环境配置

一、系统环境: 操作系统:Windows 11 专业版 显卡:RTX 4080 CUDA:cuda_12.6.2_560.94_windows.exe、cudnn-windows-x86_64-8.9.7.29_cuda12-archive python: 3.12.8 二、配置过程 1.设置python国内源 pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/…

Docker dockerfile镜像编码 centos7

一、 大多数docker基础镜像使用locale查看编码&#xff0c;发现默认编码都是POSIX&#xff0c;这会导致中文乱码。 解决方法如下: 二、首先使用locale -a查看容器所有语言环境 三、dockerfile中加入以下参数重新生成镜像   ENV LANGen_US.UTF-8   ENV TZAsia/Shanghai  …

解决新安装CentOS 7系统mirrorlist.centos.org can‘t resolve问题

原因 mirrorlist.centos.org yum源用不了 解决办法就是 # cd /etc/yum.repos.d/ # mv CentOS-Base.repo CentOS-Base.repo_bak # vim CentOS-Base.repoCentOS系统操作 # mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/*.repo_bak # curl -o /etc/yum.repos.d/CentOS-Linux-Ba…