node结合mongodb实现用户注册功能
程序员文章站
2023-08-29 18:17:43
一:app.js(server)
const express = require('express');
const router = require(...
一: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>
下一篇: JavaSE之——并没有多维数组