1.0.0 • Published 3 years ago

untio-hua-http v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

#账户平台

//前端 post发送
 axios.post('/api/login', {
                //接收相同变量
                userName: user.value,
                posNum: pos.value,
            }).then(res => {
                console.log(res.data, '2');
                //接收后端返回
                if (res.data) {
                    location.href = './register.html'
                } else {
                    alert('没有该账户!')
                }
            });
//引入模块
const fs = require('fs');
const url = require('url');
const path = require('path');
const http = require('http');
let data = require('./mock/data.json');

//创建服务器
const server = http.createServer((req, res) => {
    //路径
    let pathname = url.parse(req.url).pathname;
    //是否为根目录
    if (pathname === '/') {
        pathname = 'index.html';
    }
    //是否为文件
    if (path.extname(pathname)) {
        //是否存在该路径
        if (fs.existsSync(path.join('public', pathname))) {
            //返回该路径
            res.end(fs.readFileSync(path.join('public', pathname)));
        }
    } else {
        //端口 
        if (pathname === '/api/login' && req.method === 'POST') {
            let body = '';
            //逐步接收
            req.on('data', chunk => {
                body += chunk;
            });
            //接收完毕后返回
            req.on('end', () => {
                let {
                    userName,
                    posNum,
                } = JSON.parse(body);
                //查看是否存在该账户
                let Exis = data.find(item => {
                    return item.name === userName && item.password === posNum;
                })
                console.log(Exis);
                //给前端做出反馈
                if (Exis) {
                    res.end('1')
                } else {
                    res.end('0')
                }
            })
        }
        //注册账号
        if (pathname === '/api/register') {
            let regbody = '';
            req.on('data', chunk => {
                regbody += chunk;
            });
            req.on('end', () => {
                let {
                    reguserName,
                    regposNum
                } = JSON.parse(regbody);
                let regExis = data.find(item => {
                    return item.name === reguserName;
                })
                if (regExis) {
                    alert(0)
                } else {
                    //首先推入数据
                    data.push(JSON.parse(regbody));
                    fs.writeFileSync('./mock/data.json', JSON.stringify(data));
                    req.end(1)
                }
            });

        }
    }
});

server.listen(8080, () => {
    console.log('Server start')
});
1.0.0

3 years ago