如何将script.js校验后的表单数据传递至express.js?
实现原生JS向Express发送校验后的表单数据
要完成这个需求,核心是用原生JS的Fetch API发送POST请求,配合Express后端接收并将数据存入MongoDB,全程不用任何框架,步骤如下:
一、前端实现(HTML + 原生JS)
首先是注册表单的HTML,然后在script.js里完成校验和请求发送:
HTML 表单
<!-- 放在public/index.html --> <form id="registerForm"> <div> <label for="username">用户名:</label> <input type="text" id="username" placeholder="至少3个字符" required> </div> <div> <label for="password">密码:</label> <input type="password" id="password" placeholder="至少6个字符" required> </div> <button type="submit">提交注册</button> </form>
校验与请求发送(script.js)
// 放在public/script.js const registerForm = document.getElementById('registerForm'); const usernameInput = document.getElementById('username'); const passwordInput = document.getElementById('password'); registerForm.addEventListener('submit', async (e) => { // 阻止表单默认跳转行为 e.preventDefault(); // 执行你的校验逻辑(这里是示例,你可以替换成自己的校验规则) let isFormValid = true; if (usernameInput.value.trim().length < 3) { alert('用户名长度不能少于3位'); isFormValid = false; } if (passwordInput.value.trim().length < 6) { alert('密码长度不能少于6位'); isFormValid = false; } // 校验不通过直接返回 if (!isFormValid) return; // 准备要发送的数据 const userData = { username: usernameInput.value.trim(), password: passwordInput.value.trim() }; try { // 用Fetch API发送POST请求到后端接口 const response = await fetch('/api/register', { method: 'POST', // 告诉后端请求体是JSON格式 headers: { 'Content-Type': 'application/json', }, // 将JS对象转为JSON字符串 body: JSON.stringify(userData) }); // 解析后端返回的JSON数据 const result = await response.json(); if (response.ok) { alert('注册成功!'); registerForm.reset(); // 清空表单 } else { alert(`注册失败: ${result.message}`); } } catch (error) { alert('网络异常,请稍后重试'); console.error('请求出错:', error); } });
二、后端实现(Express + MongoDB)
1. 安装依赖
先初始化项目并安装所需包:
npm init -y npm install express mongoose
2. 后端核心代码(server.js)
const express = require('express'); const mongoose = require('mongoose'); const app = express(); const PORT = 3000; // 配置Express解析JSON请求体,必须加这个才能接收前端发的JSON数据 app.use(express.json()); // 连接MongoDB(替换成你的数据库地址,本地默认是mongodb://localhost:27017/你的库名) mongoose.connect('mongodb://localhost:27017/registrationDB') .then(() => console.log('MongoDB连接成功')) .catch(err => console.error('MongoDB连接失败:', err)); // 定义用户模型(对应MongoDB的集合) const User = mongoose.model('User', { username: { type: String, required: true, unique: true // 确保用户名唯一 }, password: { type: String, required: true // 注意:实际项目必须加密存储密码,作业如果允许可以先存明文,后续可以用bcrypt加密 } }); // 处理注册请求的API接口 app.post('/api/register', async (req, res) => { try { const { username, password } = req.body; // 检查用户名是否已存在 const existingUser = await User.findOne({ username }); if (existingUser) { return res.status(400).json({ message: '该用户名已被注册' }); } // 创建新用户并保存到数据库 const newUser = new User({ username, password }); await newUser.save(); // 返回成功响应 res.status(201).json({ message: '注册成功' }); } catch (err) { console.error('处理注册请求出错:', err); res.status(500).json({ message: '服务器内部错误' }); } }); // 托管前端静态文件(把HTML、JS、CSS放在public文件夹下) app.use(express.static('public')); // 启动服务器 app.listen(PORT, () => { console.log(`服务器运行在 http://localhost:${PORT}`); });
三、运行与测试
- 确保MongoDB服务已经启动
- 启动后端:
node server.js - 打开浏览器访问
http://localhost:3000,填写表单并提交,数据会被校验后发送到后端,最终存入MongoDB
补充说明
- 实际生产环境中,绝对不能明文存储密码,可以用
bcrypt包加密:安装后在保存密码前执行const hashedPassword = await bcrypt.hash(password, 10);,然后存储hashedPassword - 可以根据需求扩展校验规则,比如邮箱格式检查、密码复杂度验证等
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

