Home >Web Front-end >JS Tutorial >NodeJS study notes - Connect middleware application example_node.js

NodeJS study notes - Connect middleware application example_node.js

WBOY
WBOYOriginal
2016-05-16 16:17:421188browse

1, opening analysis

Hello everyone, Mr. Big Bear is here again. I didn’t write a blog yesterday because of some personal matters. Today I have another article. This article is mainly about writing a small notepad application. The previous article,

I have also introduced the use of "Connect" middleware and the usage of "Mongodb". Today I will combine these two middlewares and write a practical example. I will continue to improve and reconstruct them and have reached

Full learning purpose. Okay, let’s stop talking nonsense and go directly to the topic.

2. Demand analysis

(1), user registration and login functions (no complex interaction scenarios involved, the user will determine whether it already exists during registration).

(2), the user logs in successfully and enters the background of the note management system (add, delete, modify and check functions of the note module).

(3), users can have simple permission division (administrator, registered user).

(4), the interface is relatively simple and focuses on learning.

3. Start designing the application (Part 1)

(1), create a user login page, the code is as follows:

Copy code The code is as follows:



   
        Bigbear记事本应用登录
       
       
       
       
   
   
       
Bigbear记事本应用登录

           

                用户名:


                密  码:
               
                我要注册
           

   

  效果图:

(2),建立用户注册页面,代码如下:

复制代码 代码如下:

 
 
    
         Bigbear记事本应用注册
        
        
        
        
    
    
        
Bigbear记事本应用注册

            

                 用户名:


                 密  码:


                
            

    
 

  效果图:

(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),明天继续完成后续的功能,尽请期待。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn