请求了数据库则为动态服务器(网页),没有则为静态服务器(网页)

读数据库

image.png
image.png

写数据

form

  1. <form action="">
  2. <div>
  3. <label>用户名: <input type="text" name="name"></label>
  4. </div>
  5. <div>
  6. <label>密码: <input type="password" name="password"></label>
  7. </div>
  8. <button type="submit">注册</button>
  9. </form>

读取输入

  1. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  2. <script>
  3. const $form = $('#register')
  4. $form.on('submit', (e)=>{
  5. e.preventDefault() // 阻止默认行为
  6. const name = $form.find('input[name=name]').val() // 获取值
  7. const password = $form.find('input[name=password]').val()
  8. console.log(name, password)
  9. // 给服务器发POST请求
  10. $.ajax({
  11. method: 'POST',
  12. url: '/register',
  13. contentType: 'text/json; charset=UTF-8',
  14. data: JSON.stringify({name,password})
  15. })
  16. })
  17. </script>

image.png
image.png
image.png

服务器处理post请求

  1. if (path === "/register" && method === "POST") {
  2. response.setHeader("Content-Type", "text/html; charset=UTF-8")
  3. const userArray = JSON.parse(fs.readFileSync("./db/users.json"))
  4. const array = [];
  5. // 数据是一段一段传输的
  6. request.on("data", chunk => {
  7. array.push(chunk)
  8. })
  9. request.on("end", () => {
  10. const string = Buffer.concat(array).toString()
  11. const obj = JSON.parse(string) // 得到post的数据
  12. const lastUser = userArray[userArray.length-1]; // 获取最大ID
  13. const newUser = {
  14. id: lastUser? lastUser.id + 1 : 1,
  15. name: obj.name,
  16. password: obj.password
  17. }
  18. userArray.push(newUser)
  19. fs.writeFileSync("./db/users.json", JSON.stringify(userArray)) // 写入数据库
  20. response.end()
  21. })
  22. }