请求了数据库则为动态服务器(网页),没有则为静态服务器(网页)
读数据库
写数据
form
<form action="">
<div>
<label>用户名: <input type="text" name="name"></label>
</div>
<div>
<label>密码: <input type="password" name="password"></label>
</div>
<button type="submit">注册</button>
</form>
读取输入
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
const $form = $('#register')
$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)
// 给服务器发POST请求
$.ajax({
method: 'POST',
url: '/register',
contentType: 'text/json; charset=UTF-8',
data: JSON.stringify({name,password})
})
})
</script>
服务器处理post请求
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) // 得到post的数据
const lastUser = userArray[userArray.length-1]; // 获取最大ID
const newUser = {
id: lastUser? lastUser.id + 1 : 1,
name: obj.name,
password: obj.password
}
userArray.push(newUser)
fs.writeFileSync("./db/users.json", JSON.stringify(userArray)) // 写入数据库
response.end()
})
}