需求

使用node.js搭建本地服务器,使用ajax进行请求和获取数据,功能是实现用户登录与注册功能。

结构

server.js为搭建服务器的文件,data.json存储的是用户信息,index.htmlregister.html分别为登录和注册页面

写服务接口

创建server.js文件,编写服务端代码,使用express框架搭建本地服务器,创建三个路由分别监听登录方式的get方法和post方法,以及注册功能get方法。

const express = require('express')
const fs = require('fs')
const querystring = require('querystring')
const app = express()
app.use(express.static(__dirname))
app.listen(91)

app.get('/a', (req, res) => {
   
    let content = {
   
        username: req.query.username,
        password: req.query.password
    }
    fs.readFile('./data.json', 'utf8', (err, data) => {
   
        if (err) {
   
            res.end(err);
            return
        }
        data = JSON.parse(data)
        for (let i = 0; i < data.length; i++) {
   
            // 判断用户名密码是否正确
            if (data[i].username == content.username && data[i].password == content.password) {
   
                res.end('0')
                return
            }
        }
        res.end('1')
    })
})

app.post('/a', (req, res) => {
   
    // res.send('post成功')
    let content = ''
    req.on('data', params => {
   
        content += params
    })
    req.on('end', () => {
   
        content = querystring.parse(content)
        fs.readFile('./data.json', 'utf8', (err, data) => {
   
            if (err) {
   
                res.end(err);
                return
            }
            data = JSON.parse(data)
            for (let i = 0; i < data.length; i++) {
   
                // 判断用户名密码是否正确
                if (data[i].username == content.username && data[i].password == content.password) {
   
                    res.end('0')
                    return
                }
            }
            res.end('1')
        })
    })
})


app.get('/b', (req, res) => {
   
    // res.send('ok')
    fs.readFile("./data.json", 'utf8', (err, datas) => {
   
        if (err) {
   
            res.end(err);
            return
        } else {
   
            let userData = JSON.parse(datas)
            let newData = {
   
                username: req.query.username,
                password: req.query.password
            }
            // 判断用户名是否存在
            for (let i = 0; i < userData.length; i++) {
   
                if (userData[i].username == newData.username) {
   
                    res.end('1')
                    return
                }
            }
            userData.push(newData)
            // 写入文件必须是string或者 buffer类型
            userData = JSON.stringify(userData)
            fs.writeFile('./data.json', userData, 'utf8', err => {
   
                if (err) {
   
                    res.end('3')
                } else {
   
                    res.end('0')
                }
            })
        }
    })
})

console.log('正在监听端口:91')

前端页面代码

index.js

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./index.css">
</head>

<body>
    <div class='form'>

        <form>
            <div class='item'>
                <img src="./agul.jpg" alt="">
            </div>
            <div class='item'>
                <h3>AJAX登录与注册系统</h3>
            </div>
            <div class="item">
                <i class='iconfont icon-yonghu'></i><input type="text" id='username' placeholder="用户名">
            </div>
            <div class="item">
                <i class='iconfont icon-mima'></i><input type="password" id='psw' placeholder=" 密&nbsp;&nbsp;&nbsp;码">
            </div>
            <div class='method'>
                <span>method</span>
                <label>
                    <input name="method" type="radio" value="" id='getMethod' checked />get </label>
                <label>
                    <input name="method" type="radio" value="" id='postMethod' />post </label>
            </div>
            <div class="item1">
                <a href="#" id='login'>登录</a>
            </div>
            <div class="item1">
                <a href="./register.html">注册</a>
            </div>
        </form>
    </div>
    <script>
        let getMethod = document.querySelector('#getMethod')
        let user = document.querySelector('#username')
        let psw = document.querySelector('#psw')
        let login = document.querySelector('#login')
        login.onclick = function () {
   
            console.log('发送中')
            let type = getMethod.checked ? 'get' : 'post'
            ajax(type, 'http://127.0.0.1:91/a')
        }

        function ajax(method, url) {
   
            let data = 'username=' + user.value + '&password=' + psw.value
            let xhr = new XMLHttpRequest()
            url = method.toUpperCase() === 'GET' ? url + '?' + data : url
            xhr.open(method, url, true)
            if (method.toUpperCase() === 'GET') {
   
                xhr.send()
            } else {
   
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send(data)
            }
            xhr.onreadystatechange = function () {
   
                if (xhr.status === 200 && xhr.readyState === 4) {
   
                    console.log(xhr.responseText)
                    if (xhr.responseText == 0) {
   
                        alert('登录成功!')
                    } else {
   
                        alert('用户名或密码错误!')
                    }
                }
            }
        }

    </script>
</body>

</html>

register.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./index.css">
</head>

<body>
    <div class='form' style="height: 300px;">

        <form>
            <div class='item'>
                <img src="./agul.jpg" alt="">
            </div>
            <div class='item'>
                <h3>AJAX登录与注册系统</h3>
            </div>
            <div class="item">
                <i class='iconfont icon-yonghu'></i><input type="text" id='username' placeholder="用户名">
            </div>
            <div class="item">
                <i class='iconfont icon-mima'></i><input type="password" id='psw' placeholder=" 密&nbsp;&nbsp;&nbsp;码">
            </div>

            <div class="item1">
                <a href="#" id='register'>注册</a>
            </div>

        </form>

        <script>
            let register = document.querySelector('#register')
            let user = document.querySelector('#username')
            let psw = document.querySelector('#psw')
            register.onclick = function () {
   
                let data = 'username=' + user.value + '&password=' + psw.value
                let xhr = new XMLHttpRequest()
                url = 'http://127.0.0.1:91/b?' + data
                xhr.open('get', url, true)
                xhr.send()
                xhr.onreadystatechange = function () {
   
                    if (xhr.status === 200 && xhr.readyState === 4) {
   
                        console.log(xhr.responseText)
                        if (xhr.responseText == 1) {
   
                            alert('用户已存在!')
                        } else if (xhr.responseText == 0) {
   
                            alert('恭喜你注册成功!')
                            location.href = './index.html'
                        } else if (xhr.responseText == 3) {
   
                            alert('很遗憾注册失败!')
                        }
                    }
                }
            }
        </script>
</body>

</html>

CSS代码

*{
   
    padding: 0;
    margin: 0;
}

@font-face {
   
  font-family: "iconfont"; /* Project id 2596412 */
  src: url('//at.alicdn.com/t/font_2596412_4zfffoecsgg.woff2?t=1623039392557') format('woff2'),
       url('//at.alicdn.com/t/font_2596412_4zfffoecsgg.woff?t=1623039392557') format('woff'),
       url('//at.alicdn.com/t/font_2596412_4zfffoecsgg.ttf?t=1623039392557') format('truetype');
}

.iconfont {
   
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-yonghu:before {
   
  content: "\e912";
}

.icon-mima:before {
   
  content: "\eb26";
}

.icon-yonghu1:before {
   
  content: "\e640";
}

.icon-mima1:before {
   
  content: "\e6d4";
}

html,body{
   
    background-color: #eee;
}

.form{
   
    margin: 100px auto;
    background-color: #fff;
    height: 400px;
    width: 300px;
    padding: 30px;
    border-radius: 20px;
    box-shadow: 0 0 10px 0 #919191;
}

.item{
   
    margin: 0 auto;
    width: 300px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    position: relative;
}

.form img{
   
    width: 60px;
    height: 60px;
    border-radius: 50%;
}

.item input{
   
    width: 60%;
    outline: none;
    height: 30px;
    border-radius: 15px;
    padding-left: 40px;
    border: 1px solid #919191;
    box-shadow: 0 0 4px 0 #919191;
}
.item i{
   
    color: #919191;
    position: absolute;
    left: 50px;
    top: 2px;
}

.method{
   
    padding-left: 50px;
}

.method input{
   
    width: 30px;
}

.item1{
   
    height: 40px;
    line-height: 40px;
    margin: 10px 0;
}

.item1 a{
   
    display: block;
    background-color: #667aff;
    width: 60%;
    height: 40px;
    text-align: center;
    margin: 0 auto;
    border-radius: 20px;
    text-decoration: none;
    color: #fff;
    box-shadow: 0 0 4px 0 #919191;
}

.item1 a:hover{
   
    opacity: 0.8;
}

展示

使用node server.js命令运行服务器文件启动服务,在本地地址91端口访问:

切换到注册页进行注册:

回到登录页登录验证,支持get、post方式请求

注册成功会在data.json文件插入数据,登录时会进行用户和密码的比对,注册时会对用户名是否存在进行判断。
简单的小功能就完成了。