Node基礎入門(四):案例

上一篇《Node基礎入門(三):數據交互》html

用以上所學知識開發一個登陸/註冊的程序。node

1、需求分析

  • 輸入帳戶和密碼,點擊登陸,查詢數據庫是否有該帳戶,有則繼續檢查密碼是否正確,不正確則提示「密碼錯誤」,正確則登陸成功,跳轉後臺頁面,無該帳戶則提示「帳戶不存在」;
  • 輸入帳戶和密碼,點擊註冊,查詢數據庫是否有該帳戶,有則提示「帳戶已存在」,無則註冊成功;
  • 因爲還未學習數據庫,因此咱們用一個user對象(JSON)代替用戶表。

2、接口設計

  • 名稱:login / reg(註冊和登陸接口幾乎相同)
  • 請求方式:get / post(登陸用get,註冊用post)
  • 參數:jquery

    • username 帳戶(字符串)
    • password 密碼 (字符串)
  • 返回:ajax

    • err 錯誤碼(數字,0:正確,1:錯誤)
    • msg 返回信息(字符串)

3、代碼開發

app.js數據庫

let http = require('http')
let url = require('url')
// 將post的數據從字符串類型轉化爲咱們須要的json類型
let querystring = require('querystring')
// 爲了成功訪問http://localhost:8080/login.html
let fs = require('fs')

// 這裏用一個json代替數據庫,假設用戶表已經有一個用戶admin,密碼是123
let user = {
  admin: '123'
}

http.createServer((req, res) => {
  // 獲取數據
  let path, get, post

  if (req.method === 'GET') {
    let {pathname, query} = url.parse(req.url, true)
    path = pathname
    get = query
    complete()
  } else if (req.method === 'POST') {
    let result = []
    path = req.url
    req.on('data', buffer => {
      result.push(buffer)
    })
    req.on('end', () => {
      // 合併片斷,而後轉成字符串,最後處理成json
      post = querystring.parse(Buffer.concat(result).toString())
      complete()
    })
  }

  function complete () {
    if (path === '/login') {
      // 解決中文亂碼
      res.writeHead(200, {
        'Content-Type': 'text/plain; charset=utf-8'
      })
      let {username, password} = get
      if (!user[username]) {
        res.end(JSON.stringify({
          err: 1,
          msg: '帳戶不存在'
        }))
      } else if (user[username] !== password) {
        res.end(JSON.stringify({
          err: 1,
          msg: '密碼錯誤'
        }))
      } else {
        res.end(JSON.stringify({
          err: 0,
          msg: '登陸成功'
        }))
      }
    } else if (path === '/reg') {
      res.writeHead(200, {
        'Content-Type': 'text/plain; charset=utf-8'
      })
      let {username, password} = post
      if (user[username]) {
        res.end(JSON.stringify({
          err: 1,
          msg: '帳戶已存在'
        }))
      } else {
        user[username] = password
        res.end(JSON.stringify({
          err: 0,
          msg: '註冊成功'
        }))
      }
    } else {
      // 說明是文件,則調用fs.readFile(),所以才能成功訪問http://localhost:8080/login.html
      fs.readFile(`.${req.url}`, (err, data) => {
        if (err) {
          res.end('404')
        } else {
          res.end(data)
        }
      })
    }
  }
}).listen(8080)

login.htmlnpm

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>登陸/註冊</title>
</head>
<body>
<div class="wrapper">
  帳戶:<input type="text" id="username"><br>
  密碼:<input type="password" id="password"><br>
  <button id="login">登陸</button><br>
  <button id="reg">註冊</button>
</div>

<!--咱們須要引入jQuery(目的是發送ajax請求),利用以前學到的npm install jquery安裝jquery,成功後將node_modules/jquery/dist/裏面的jquery.min.js拷貝至項目根目錄-->
<script src="jquery.min.js"></script>
<script>
  // 點擊登陸
  $('#login').click(() => {
    $.ajax({
      url: '/login',
      method: 'get',
      data: {
        username: $('#username').val(),
        password: $('#password').val()
      },
      dataType: 'json',
      success (res) {
        if (res.err) {
          alert(res.msg)
        } else {
          alert('登陸成功')
          location.href = 'admin.html'
        }
      }
    })
  })
  // 點擊註冊
  $('#reg').click(() => {
    $.ajax({
      url: '/reg',
      method: 'post',
      data: {
        username: $('#username').val(),
        password: $('#password').val()
      },
      dataType: 'json',
      success (res) {
        if (res.err) {
          alert(res.msg)
        } else {
          alert('註冊成功')
        }
      }
    })
  })
</script>
</body>
</html>

admin.htmljson

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>後臺</title>
</head>
<body>
<h2>這裏是後臺首頁</h2>
</body>
</html>

4、測試截圖

1. 帳戶:admin,密碼:123,點擊登陸,登陸成功segmentfault

2. 帳戶:admin,密碼:111,點擊登陸,密碼錯誤app

3. 帳戶:eric,密碼:123,點擊登陸,帳戶不存在post

4. 帳戶:eric,密碼:123,點擊註冊,註冊成功

5. 帳戶:eric,密碼:123,點擊登陸,登陸成功

6. 帳戶:eric,密碼:123,點擊註冊,帳戶已存在

相關文章
相關標籤/搜索