用户提交用户名和密码 users.json里就新增了一行数据
思路
前端写一个 form,让用户填写 name 和 password
前端监听 submit 事件
前端发送 post 请求,数据位于请求体
后端接收 post 请求
后端获取请求体中的 name 和 password
后端存储数据
写一个form
<form id="registerForm"><div><label>用户名 <input type="text" name="name"></label></div><div><label>密码 <input type="password" name="password"></label></div><div><button type="submit">注册</button></div></form>
监听submit事件,发送AJAX请求
<script>const $form = $('#registerForm')$form.on('submit', (e)=>{e.preventDefault()const name = $form.find('input[name=name]').val()const password = $form.find('input[name=password]').val()console.log(name, password)$.ajax({// 发送AJAX请求method: 'POST',// 使用POST请求url: '/register',contentType: 'text/json; charset=UTF-8',data: JSON.stringify({name, password})}).then(()=>{alert('注册成功')location.href = '/sign_in.html'}, ()=>{})})</script>
后端接收请求
if (path === "/register" && method === "POST") {response.setHeader("Content-Type", "text/html; charset=utf-8");const userArray = JSON.parse(fs.readFileSync("./db/users.json"));// 读取数据库中的用户信息const array = [];// 创建一个空数组,数据可能是分段上传request.on("data", chunk => {array.push(chunk);});request.on("end", () => {const string = Buffer.concat(array).toString();const obj = JSON.parse(string);const lastUser = userArray[userArray.length - 1];const newUser = {// 拿到用户注册的数据// id 为最后一个用户的 id + 1id: lastUser ? lastUser.id + 1 : 1,name: obj.name,password: obj.password};userArray.push(newUser);// 放入数据库fs.writeFileSync("./db/users.json", JSON.stringify(userArray));response.end()});}
