你想了解的node.js與數據庫的交互效果

今天咱們來說一些node.js相關的簡單的登錄註冊所用到的數據庫爲mongodbcss

做爲你操做的基礎固然是要有html頁面了,html

  一、首先咱們來寫一下html頁面node

  a.共同的頁面content.html(在js中咱們是把html頁面放入js中而後經過js的調用來實現公共的頭/尾部)jquery

  此處用了bootstrap,讀者若是有興趣的話也能夠了解一下,當年的英雄ajax

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">後臺管理系統</a>
</div>
 
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
<li><a href="#">登陸列表</a></li>
<li><a href="#">註冊列表</a></li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="請輸入用戶名">
</div>
<button type="submit" class="btn btn-default">查詢</button>
</form>
<!-- 判斷數據庫中返回值是否存在username -->
{% if !username %}
<ul class="nav navbar-nav navbar-right">
<li class="{{isLogin}}"><a href="/login">登陸</a></li>
<li class="{{isReg}}"><a href="/regist">註冊</a></li>
</ul>
{% else %}
<ul class="nav navbar-nav navbar-right">
<!-- {{username}}中的username爲登陸成功後從數據庫中返回的用戶名 -->
<li><a href="/#">用戶名:{{username}}</a></li>
<li><a href="/logout">退出</a></li>
</ul>
{% endif %}
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
{% block content %}
{% endblock %}
<!-- content塊用來存放登陸或者註冊部分 -->
{% block registjs %}
{% endblock %}
<!-- registjs塊用來存放註冊js部分 -->
{% block loginjs %}
{% endblock %}
<!-- loginjs塊用來存放登陸JS部分 -->

b.書寫首頁home.htmlmongodb

{% extends 'content.html' %}
<!-- 理解爲引入content.html -->
{% block content %}
<h1>首頁</h1>
{% endblock %}

c.書寫login.html數據庫

{% extends './content.html' %}
{% block content %}
<div>
    <div class="form-group">
      <label for="exampleInputEmail1">Email address</label>
      <input type="text" class="form-control" id="username" placeholder="name">
    </div>
    <div class="form-group">
      <label for="exampleInputPassword1">Password</label>
      <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-default" id="login">登陸</button>
    <button type="submit" class="btn btn-default" id="cancel">取消</button>    
</div>
{% endblock %}
{% block loginjs %}
<script src="/static/login.js"></script>
{% endblock %}

d.書寫regist.htmlexpress

{% extends './content.html' %}
{% block content %}
<div>
    <div class="form-group">
      <label for="exampleInputEmail1">用戶名</label>
      <input type="text" class="form-control" id="exampleInputname" placeholder="name">
    </div>
    <div class="form-group">
      <label for="exampleInputPassword1">Password</label>
      <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">Password</label>
        <input type="password" class="form-control" id="rePassword1" placeholder="Password">
      </div>
    <button type="submit" class="btn btn-default" id="confim">註冊</button>
    <button type="submit" class="btn btn-default" id="cancel">取消</button>    
</div>
{% endblock %}

{% block registjs %}
<script src="/static/regist.js"></script>
{% endblock %}

到如今爲止咱們的HTML頁面寫完了嗎?實際上是沒有的由於咱們還有js沒有書寫json

二、書寫js代碼bootstrap

  a.書寫login.js

var login=$('#login');
var username=$("#username")
var exampleInputPassword1=$("#exampleInputPassword1")
var cancel=$('#cancel')
login.on('click',function(){
    var user = username.val()
    var psd= exampleInputPassword1.val();
    console.log(user,psd)
    $.ajax({
        url:'/ajax/ab',
        method:'POST',
        data:{
            usename:user,
            password:psd
        },
        success:function(data){
            console.log(data);
            if(data.status == 0){
                // 登陸成功跳轉到根目錄(首頁)
                window.location.href='/';
            }else{
                console.log(data.message)
            }
        }
    })
})
cancel.on("click",function(){
    location.href="/"
})

  b.書寫regist.js

  

var confim=$('#confim');
var exampleInputname=$("#exampleInputname")
var exampleInputPassword1=$("#exampleInputPassword1")
var rePassword1=$("#rePassword1")
var cancel=$('#cancel')
confim.on('click',function(){
    var user = exampleInputname.val()
    var psd= exampleInputPassword1.val();
    var repsd = rePassword1.val();
    if(psd !=repsd){
        alert("兩次密碼驗證不一致,請從新輸入")
        return;
    }
    $.ajax({
        url:'/ajax/a',
        method:'POST',
        data:{
            usename:user,
            password:psd
        },
        success:function(data){
            if(status==0){
                //註冊成功,跳轉到登陸頁面
                location.href="/login";
            }else{
                alert(status.message)
            }
        }
    })
})
cancel.on("click",function(){
    console.log("取消")
    location.href="/"
})

3.咱們在數據庫中建立一張表

const mongoose = require('mongoose');
//建立表格
const userSchema = new mongoose.Schema({
    usename: String,
    password:String
})
// 建立表名爲userpeoson,模型爲userSchema的表
const User=mongoose.model('userpeoson',userSchema)
module.exports = User;

4.引入中間文件(server.js)將客戶端和數據庫鏈接起來

const express = require("express")
const swig = require('swig');
const mongoose = require('mongoose');
const htmlrouter= require('./handlerequest/htmlrouter')
const ajaxrouter= require('./handlerequest/ajaxRouter')
new Promise((resolve,reject)=>{
    //鏈接數據庫(27017爲咱們設置的port值如圖一)
    mongoose.connect('mongodb://localhost:27017',(error)=>{
        if(error){
            console.log('鏈接數據庫失敗');
        }else{
            console.log('鏈接數據庫成功')
            resolve();
        }
    })
})
.then(()=>{
    //啓動服務器
    const app = express();
    //處理靜態的文件(好比js等不會改變的文件)
    app.use('/static',express.static('./public'));
    //處理www文件下變化的頁面
    app.set('view engine','html')
    app.set('views','./www');
    app.engine('html',swig.renderFile);
    swig.setDefaults({cache:false});
    //使用中間鍵htmlrouter處理變化的HTML文件
    app.use('/',htmlrouter)
    //使用中間鍵ajaxrouter處理變化的ajax文件
    app.use('/ajax',ajaxrouter)   
    app.listen(9000,(error)=>{
        if(error){
            console.log('服務器啓動失敗');
        }else{
            console.log('服務器啓動成功');
            console.log('http://localhost:9000')
        }
    })
})

5.編寫htmlrouter.js處理變化的HTML文件

//處理html請求
const express= require('express');
const bodyParser = require('body-parser')
const user = require("../model/database")
const cookie = require('cookies')
const router = new express.Router();
router.get('/',(req,res)=>{
    //判斷用戶是否登陸了
    let cookies = new cookie(req,res)
    let userid = cookies.get('userid');
    if(userid){
        //用戶已經登陸
        user.findById(userid).then(info=>{
            res.render('home',{
                isHome:'active',
                username:info.usename
            })
        })
    }else{
        //用戶沒有登陸
        //根路徑解析爲home.html
        res.render('home',{
            isHome:'active'
        })
    }
})
router.get("/login",(req,res)=>{
    
    res.render('login',{
        isLogin: 'active'
    })
})
router.get('/regist',(req,res)=>{
    res.render('regist',{
        isReg: 'active'
    })
})
router.get('/logout',(req,res)=>{
//點擊退出時讓cookies中的userid變爲空
    let cookies = new cookie(req,res);
    cookies.set('userid',null);
    //讓頁面跳轉到首頁
    res.redirect('/');
})
module.exports = router;

6.編寫ajaxrouter.js處理變化的ajax文件

//處理ajax請求
const express = require('express')
const use = require('../model/database')//?
const bodypar = require('body-parser')
const Cookie = require("cookies");
const router = new express.Router();
module.exports = router;
router.use("/a",bodypar());
router.post('/a',(req,res)=>{
    
    let username=req.body.usename;
    let password = req.body.password;
    console.log(username,password)
    //判斷用戶名是否存在
use.findOne({
    usename:username
})
.then(
    info=>{
        if(info){
            //若是用戶註冊了
            res.json({
                status:1,
                message:'該用戶已經註冊'
            })
        }else{
            console.log(username,password)
            let useinfo = new use({
                usename:username,
                password:password
            });
            useinfo.save().then(()=>{
                res.json({
                    status:0,
                    message:'註冊成功'
                })
            })
        }
    }
)
})
router.use("/ab",bodypar());
router.post('/ab',(req,res)=>{
    
    let username=req.body.usename;
    let password = req.body.password;
    console.log(username,password)
    //判斷用戶名是否存在
use.findOne({
    usename:username
})
.then(
    info=>{
        if(info){
            //數據庫存在用戶
            if(info.password == password){
                //建立cookie
                let cookies= new Cookie(req,res);
                cookies.set('userid',info._id);
                res.json({
                    message:'登陸成功',
                    status:0
                })
            }else{
                res.json({
                    message:'登陸失敗,密碼錯誤',
                    status:2
                })
            }
        }else{
            res.json({
                message:'該用戶不存在',
                status:1
            })
        }
    }
)
})

7.到如今爲止咱們基本的基礎工做已經完成了,須要的就是開啓數據庫,運行咱們書寫的server.js文件了

  a.運行mongod --dbpath D:\練習\db-project\db(D:\練習\db-project\db爲你數據庫想要存放的地方)

  注意點:安裝mongodb須要運行的地址是

  

  你若是想直接用Windows+r快捷鍵直接運行的話就須要將這個路徑添加到系統的path路徑下

  

運行結果(圖一)端口27017

8.在你的server地址下運行server.js文件(http://localhost:9000是我在server.js中設置的地址,也是你要訪問的地址)

9.運行http://localhost:9000結果以下圖.

恭喜你如今一個簡單的node註冊登陸就完成了

相關文章
相關標籤/搜索