node結合mongodb實現用戶註冊功能

一:app.js(server)

const express = require('express');
const router = require('./router.js');

let app = express();

app.use(router);


app.listen(8000,function () {
    console.log('hello 8000')
});

二:router.js(路由)

const express = require('express');
const router = express.Router();
const querystr = require('querystring');
const MongoClient = require('mongodb').MongoClient;

let url = 'mongodb://127.0.0.1:27017';

router.use(express.static('./public'));

router.get('/',function (req,res) {
    res.sendfile('./public/index.html');
});

router.post('/reg',function (req,res) {
    let data= '';
    req.on('data',function (chunk) {
        data+=chunk;
    });
    req.on('end',function () {
        let info = querystr.parse(data);
        MongoClient.connect(url,function (err,client) {
            let db = client.db('app');
            if(err === null){

                db.collection('user').find({"user":info.user}).toArray(function(err,result) {
                //判斷數據庫app下的user集合中是否存在info文檔
                    if(!result[0] == []){
                        res.send("該用戶已被註冊")
                        //如果有,則打印"該用戶已被註冊"
                    }else{
                        //如果無,則添加info文檔,並打印"註冊成功"
                        db.collection('user').insertOne(info,function () {
                            console.log(info)
                        })
                        client.close();
                        res.send('註冊成功')
                    }
                })
            }else {
                client.close();
            }
        });

    })
});

module.exports = router;

三:index.html

//註冊p
<p id="box1" style="display: none">
    <form action="https://127.0.0.1:8000/reg" method="post">
        <label for="user">用戶名:</label>
        <input type="text" id="user1" name="user" value="">
        <br>
        <label for="pwd">密碼:</label>
        <input type="password" id="pwd1" name="pwd" value="">
        <br>
        <button id="btn">註冊</button>
    </form>
</p>

//註冊登錄p
<p id="box2">
    <form action="https://127.0.0.1:8000/form" method="post">
        <label for="user">用戶名:</label>
        <input type="text" id="user" name="user" value="">
        <br>
        <label for="pwd">密碼:</label>
        <input type="password" id="pwd" name="pwd" value="">
        <br>
        <button id="btn_login">登錄</button>
    </form>
    <button id="btn_registered">註冊</button>
</p>
</body>
<script>
    var registered = document.getElementById('btn_registered');
    var box1 = document.getElementById('box1');
    var box2 = document.getElementById('box2');

    registered.addEventListener('click',function () {
        box1.style.display = 'block';
        box2.style.display = 'none';
    })
</script>

You May Also Like