search
HomeWeb Front-endJS TutorialNodeJS study notes - Connect middleware application example_node.js

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
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

火了!新的JavaScript运行时:Bun,性能完爆Node火了!新的JavaScript运行时:Bun,性能完爆NodeJul 15, 2022 pm 02:03 PM

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

nodejs中lts是什么意思nodejs中lts是什么意思Jun 29, 2022 pm 03:30 PM

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

深入浅析Nodejs中的net模块深入浅析Nodejs中的net模块Apr 11, 2022 pm 08:40 PM

本篇文章带大家带大家了解一下Nodejs中的net模块,希望对大家有所帮助!

怎么获取Node性能监控指标?获取方法分享怎么获取Node性能监控指标?获取方法分享Apr 19, 2022 pm 09:25 PM

怎么获取Node性能监控指标?本篇文章来和大家聊聊Node性能监控指标获取方法,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft