天天看點

nodejs實作使用者登入注冊---前台通過ajax請求資料

1.通過http子產品建立伺服器,并監聽端口8080

const http = require('http');

var server = http.createServer(function (req, res){});

server.listen(8080);
           

2.解析資料

通過‘querystring’和'url'子產品解析資料

req.on('data', function (data){});-----接收到一段資料

req.on('end', function (){});------接收到全部資料

const querystring = require('querystring');
const urlLib = require('url');

var str = '';
    req.on('data', function (data) {
        str += data;
    });
    req.on('end', function () {
        var obj = urlLib.parse(req.url, true);

        const url = obj.pathname;
        const GET = obj.query;
        const POST = querystring.parse(str);
           

3.讀取檔案

通過‘fs’子產品讀取檔案

var file_name = './www' + url;
fs.readFile(file_name, function (err, data) {
   if (err) {
         res.write('404');
    } else {
          res.write(data);
    }
          res.end();
 });
           

4.ajax參數

url: 發送請求的位址

data:發送到伺服器的資料

type:請求的類型

success:請求成功時執行的回調函數

error:請求失敗時執行的回調函數

ajax({
          url: '/user',
          data: { act: 'reg', user: oTxtUser.value, pass: oTxtPass.value },
          type: 'get',
          success: function (str) {
            var json = eval('(' + str + ')');

            if (json.ok) {
              alert('注冊成功');
            } else {
              alert('注冊失敗:' + json.msg);
            }
          },
          error: function () {
            alert('通信錯誤');
          }
        });
           

完整代碼:

1.背景代碼:server.js

const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const urlLib = require('url');

//使用者資訊
var users = {
    'leimiao': '123'
};

var server = http.createServer(function (req, res) {
    //解析資料
    var str = '';
    req.on('data', function (data) {
        str += data;
    });
    req.on('end', function () {
        var obj = urlLib.parse(req.url, true);

        const url = obj.pathname;
        const GET = obj.query;
        const POST = querystring.parse(str);

        //區分——接口、檔案
        if (url == '/user') {   //接口
            switch (GET.act) {
                case 'reg':
                    //1.檢查使用者名是否已經有了
                    if (users[GET.user]) {
                        res.write('{"ok": false, "msg": "此使用者已存在"}');
                    } else {
                        //2.插入users
                        users[GET.user] = GET.pass;
                        res.write('{"ok": true, "msg": "注冊成功"}');
                    }
                    break;
                case 'login':
                    //1.檢查使用者是否存在
                    if (users[GET.user] == null) {
                        res.write('{"ok": false, "msg": "此使用者不存在"}');
                        //2.檢查使用者密碼
                    } else if (users[GET.user] != GET.pass) {
                        res.write('{"ok": false, "msg": "使用者名或密碼有誤"}');
                    } else {
                        res.write('{"ok": true, "msg": "登入成功"}');
                    }
                    break;
                default:
                    res.write('{"ok": false, "msg": "未知的act"}');
            }
            res.end();
        } else {              //檔案
            //讀取檔案
            var file_name = './www' + url;
            fs.readFile(file_name, function (err, data) {
                if (err) {
                    res.write('404');
                } else {
                    res.write(data);
                }
                res.end();
            });
        }
    });
});

server.listen(8080);
           

2.前端頁面代碼---user.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>11</title>
  <script src="ajax.js" charset="utf-8"></script>
  <script type="text/javascript">
    window.onload = function () {
      var oTxtUser = document.getElementById('user');
      var oTxtPass = document.getElementById('pass');
      var oBtnReg = document.getElementById('reg_btn');
      var oBtnLogin = document.getElementById('login_btn');

      oBtnLogin.onclick = function () {
        ajax({
          url: '/user',
          data: { act: 'login', user: oTxtUser.value, pass: oTxtPass.value },
          type: 'get',
          success: function (str) {
            var json = eval('(' + str + ')');

            if (json.ok) {
              alert('登入成功');
            } else {
              alert('登入失敗:' + json.msg);
            }
          },
          error: function () {
            alert('通信錯誤');
          }
        });
      };

      oBtnReg.onclick = function () {
        ajax({
          url: '/user',
          data: { act: 'reg', user: oTxtUser.value, pass: oTxtPass.value },
          type: 'get',
          success: function (str) {
            var json = eval('(' + str + ')');

            if (json.ok) {
              alert('注冊成功');
            } else {
              alert('注冊失敗:' + json.msg);
            }
          },
          error: function () {
            alert('通信錯誤');
          }
        });
      };
    };
  </script>
</head>

<body>
  使用者:<input type="text" id="user"><br>
  密碼:<input type="password" id="pass"><br>
  <input type="button" value="注冊" id="reg_btn">
  <input type="button" value="登入" id="login_btn">
</body>

</html>
           

繼續閱讀