如何用HTML实现注册表单同时发送两个请求以测试竞态条件
实现注册表单并发双请求以测试竞态条件
要实现点击提交按钮时发送两个完全相同的并发请求,以此测试Web应用是否存在用户名注册的竞态条件问题,你可以通过JavaScript拦截表单的默认提交行为,手动发起两个相同的POST请求。以下是修改后的完整代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Register</title> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body> <div class="register"> <h1>Register</h1> <form id="registerForm" action="register.php" method="post" autocomplete="off"> <label for="username"> <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> <label for="email"> <i class="fas fa-envelope"></i> </label> <input type="email" name="email" placeholder="Email" id="email" required> <input type="submit" value="Register"> </form> </div> <script> const form = document.getElementById('registerForm'); form.addEventListener('submit', function(e) { e.preventDefault(); // 阻止表单默认提交行为 const formData = new FormData(this); // 收集所有表单数据 // 封装请求发送逻辑,复用代码 const sendRequest = () => { return fetch(this.action, { method: this.method, body: formData }); }; // 并发发送两个完全相同的请求 Promise.all([sendRequest(), sendRequest()]) .then(responses => { // 可选:打印响应状态,方便调试 responses.forEach((res, idx) => { console.log(`第${idx+1}个请求响应状态: ${res.status}`); }); // 如果需要模拟原表单提交后的跳转,可以取消下面注释 // window.location.href = this.action; }) .catch(err => console.error('请求发送失败:', err)); }); </script> </body> </html>
代码说明:
- 拦截默认提交:通过
e.preventDefault()阻止表单的默认提交流程,避免只发送一次请求。 - 收集表单数据:使用
FormData对象自动收集表单里的所有字段(用户名、密码、邮箱),确保两个请求的参数完全一致。 - 并发请求:利用
Promise.all同时发起两个请求,让它们几乎同时到达服务器,模拟竞态条件的触发场景。 - 响应处理:可选的日志打印可以帮助你确认两个请求都已发送,也可以根据需求添加跳转或提示逻辑。
测试注意事项:
- 这种前端模拟的并发请求足够做基础测试,但如果服务器处理速度极快,可能仍存在微小的请求先后差。若需要更精准的并发测试,可以使用专业工具(如Apache JMeter、Postman批量请求)。
- 确保服务器端没有实现原子性的用户名唯一性检查(比如使用数据库唯一约束+事务锁,或者先查询再插入的非原子操作),这样才有可能触发竞态条件,创建重复用户名的账号。
内容的提问来源于stack exchange,提问作者Mitra Alidoosti
相关产品推荐
相关产品推荐

