NodeJS學習筆記之Connect中介軟體應用執行個體,nodejs學習筆記

來源:互聯網
上載者:User

NodeJS學習筆記之Connect中介軟體應用執行個體,nodejs學習筆記

一,開篇分析

大家好哦,大熊君又來了,昨天因為有點個人的事沒有寫部落格,今天又出來了一篇,這篇主要是寫一個記事本的小應用,前面的文章,

我也介紹過“Connect”中介軟體的使用以及“Mongodb”的用法,今天就結合這兩個中介軟體,寫個實際的例子,不斷完善和重構,已達到

充分學習的目的。好了,廢話不說了,直接進入主題。

二,需求分析

(1),使用者註冊,登入功能(沒有涉及很複雜的互動情境,註冊時會有使用者判斷是否已存在)。

(2),使用者登入成功,進入筆記管理系統的後台(筆記模組的增刪改查功能)。

(3),使用者可以具有簡單的許可權劃分(管理員,註冊使用者)。

(4),介面比較簡單,以學習為主。

三,開始設計應用(第一部分)

(1),建立使用者登入頁面,代碼如下:

複製代碼 代碼如下:
<!doctype html>
<html>
    <head>
        <title>Bigbear記事本應用登入</title>
        <meta content="IE=8" http-equiv="X-UA-Compatible"/>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style type="text/css">
            .note-title {
                margin-bottom : 45px ;
                background : #6699cc ;
                font-size : 14px ;
                font-weight : bold ;
                color : #fff;
                font-family:arial ;
                height : 24px ;
                line-height : 24px ;
            }
            a {
                color : #336699;
                font-family:arial ;
                font-size : 14px ;
                font-weight : bold ;
            }
        </style>
        <script src="js/index.js"></script>
    </head>
    <body>
        <div class="note-title">Bigbear記事本應用登入</div>
            <form action="/login" method="post">
                <span>使用者名稱:</span><input type="text" name="name" /><br/><br/>
                <span>密  碼:</span><input type="password" name="password" />
                <input type="submit" value="登入" />
                <a href="reg.html">我要註冊</a>
            </form>
    </body>
</html>

  :

(2),建立使用者註冊頁面,代碼如下:

複製代碼 代碼如下:
 <!doctype html>
 <html>
     <head>
         <title>Bigbear記事本應用註冊</title>
         <meta content="IE=8" http-equiv="X-UA-Compatible"/>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <style type="text/css">
             .note-title {
                 margin-bottom : 45px ;
                 background : #ff3300 ;
                 font-size : 14px ;
                 font-weight : bold ;
                 color : #fff;
                 font-family:arial ;
                 height : 24px ;
                 line-height : 24px ;
             }
         </style>
         <script src="js/index.js"></script>
     </head>
     <body>
         <div class="note-title">Bigbear記事本應用註冊</div>
             <form action="/reg" method="post">
                 <span>使用者名稱:</span><input type="text" name="name" /><br/><br/>
                 <span>密  碼:</span><input type="password" name="password" /><br/><br/>
                 <input type="submit" value="註冊" />
             </form>
     </body>
 </html>

  :

(3),建立“Mongodb”串連代碼,如下:

複製代碼 代碼如下:
 var mongodb = require("mongodb") ;
 var server = new mongodb.Server("localhost",27017,{
     auto_reconnect : true
 }) ;
 var conn = new mongodb.Db("bb",server,{
     safe : true
 }) ;
 conn.open(function(error,db){
     if(error) throw error ;
     console.info("mongodb connected !") ;
 }) ;
 exports = module.exports = conn ;

(4),建立模型實體類“User”,如下:

複製代碼 代碼如下:
 var conn = require("../conn") ;
 function User(user){
     this.name = user["name"] ;
     this.password = user["password"] ;
 } ;
 User.prototype.save = function(callback){
     var that = this ;
     conn.collection("users",{
         safe : true
     },function(error,collection){
         if(error) return conn.close() ;
         collection.findOne({   // 判斷此使用者是否存在
             name : that.name
         },function(error,user){
             if(error) return conn.close() ;
             if(!user){
                 collection.insert({
                     name : that.name + "" ,
                     password : that.password + ""
                 },{
                     safe : true
                 },function(error,user){
                     if(error) return conn.close() ;
                     callback && callback(user) ;
                     conn.close() ;
                 }) ;       
             }
             else{
                 callback("User has registed !") ;
             }
         }) ;
     }) ;
 } ;
 User.login = function(name,password,callback){
     conn.collection("users",{
         safe : true
     },function(error,collection){
         if(error) return conn.close() ;
         collection.findOne({
             name : name ,
             password : password
         },function(error,user){
             if(error) return conn.close() ;
             callback && callback(user) ;
             conn.close() ;
         }) ;
     }) ;
 } ;
 exports = module.exports = User ;

  :

(5),建立應用程式“app”,如下:

複製代碼 代碼如下:
 // app.js
 var connect = require("./lib/connect") ;
 var user = require("./models/user") ;
 var app = connect.createServer() ;
 app .use(connect.logger("dev"))
 .use(connect.query())
 .use(connect.bodyParser())
 .use(connect.cookieParser())
 .use(connect.static(__dirname + "/views"))
 .use(connect.static(__dirname + "/public"))
 .use("/login",function(request,response,next){
     var name = request.body["name"] ;
     var password = request.body["password"] ;
     user.login(name,password,function(user){
         if(user){
             response.end("Welcome to:" + user["name"] + " ^_^ ... ...") ;   
         }
         else{
             response.end("User:" + name + " Not Register !")    ;
         }
     }) ;
 })
 .use("/reg",function(request,response,next){
     var name = request.body["name"] ;
     var password = request.body["password"] ;
     new user({
         name : name ,
         password : password
     }).save(function(user){
         if(user && user["name"]){
           response.end("User:" + name + "Register Done !")    ;   
         }
         else{
           response.end("User: " + name + "has registed !") ; 
         }
     }) ;
 })
 .listen(8888,function(){
     console.log("Web Server Running On Port ---> 8888 .") ;
 }) ;

  說明一下:

    (1)“connect.query()”------處理“Get”請求參數解析。

    (2)“connect.bodyParser()”------處理“Post”請求參數解析。

    (3)“connect.static(__dirname + "/views"),connect.static(__dirname + "/public")”

     分別代表模板視圖“html”以及靜態資源如“js,css,jpg,gif”的資來源目錄。

     以下是這個應用的目錄結構:

四,總結一下

  (1),掌握NodeJs操作資料庫的基本動作陳述式。

  (2),劃分層級,如模型,視圖,路由。

  (3),不斷最佳化和修改本文的例子(比如註冊驗證使用者是否存在,可以獨立出“UserManager”做一層代理完成使用者驗證和儲存的動作)。

  (4),明天繼續完成後續的功能,盡請期待。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.