NodeJS学习笔记之项目:实现登录和注册

83 阅读1分钟

思路:

  1. 登录由于传的数据不是特别多,所以用get方式请求;
  2. 注册由于传的数据涉及到头像文件上传都得用post方式请求。

一、创建登录界面login.html,ajax请求接口采用jQuery。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>登录</title>
    <script src="./jquery.min.js"></script>
</head>

<body>
    用户名:<input type="text" id="username"><br>
    密 码:<input type="password" id="password"><br>
    <button id="login">登录</button>
    <button id="reg">注册</button>
    <script>
        $('#login').click(function () {
            $.ajax({
                url: "/login",
                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(function () {
            $.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>

二、服务端nodejs接口API处理逻辑:

  1. 判断请求方式,获取请求过来的数据;
  2. 通过路径判断请求的接口是login还是reg;
  3. 校验用户名密码的正确性及是否存在;
  4. 输出状态码及信息给前端判断是否成功。
let http = require('http');
let url = require('url');
let querystring = require('querystring');
let fs = require('fs');

//这边采用静态数组
let user = {
    admin: 123456
}

http.createServer((req, res) => {
    let path, getData, postData

    if (req.method == 'GET') {
        let { pathname, query } = url.parse(req.url, true);
        path = pathname;
        getData = query;
        complete();
    } else if (req.method == 'POST') {
        let result = [];
        path = req.url;

        req.on('data', buffer => {
            result.push(buffer)
        });

        req.on("end", () => {
            postData = 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 } = getData;

            if (!user[username]) {
                res.end(JSON.stringify({
                    err: 1,
                    msg: '用户名不存在'
                }))
            } else if (user[username] != password) {
                res.writeHead(200, {
                    'Content-Type': 'text/plain;charset=utf-8'
                })

                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 } = postData;
            if (user[username]) {
                res.end(JSON.stringify({
                    err: 1,
                    msg: '用户已经存在'
                }))
            } else {
                user[username] = password;
                res.end(JSON.stringify({
                    err: 0,
                    msg: '注册成功'
                }))
            }
        } else {
            fs.readFile(`./${path}`, (err, data) => {
                if (err) {
                    res.end('404');
                } else {
                    res.end(data);
                }
            })
        }
    }
}).listen(8088)