Nodejs Learning Notes of Connect middleware application example _node.js

Source: Internet
Author: User
Tags findone

First, the opening analysis

Hello everyone, Big Bear June came again, yesterday because a little personal things did not write a blog, today came out again, this article is mainly to write a small application of Notepad, the previous article,

I also introduced the use of "Connect" middleware and "Mongodb" usage, today, combining these two middleware, write a practical example, continuous improvement and refactoring, has reached

The purpose of full study. OK, no more nonsense, go straight to the subject.

Second, demand analysis

(1), the user registers, the login function (does not involve the very complex interactive scene, the registration will have the user to judge whether already exists).

(2), the user login successfully, into the background of the note management System (Note module additions and deletions to check the function).

(3), users can have a simple division of authority (admin, registered users).

(4), the interface is relatively simple, mainly to learn.

Third, start design application (Part One)

(1), set up the user login page, the code is as follows:

Copy Code code as follows:

<!doctype html>
<title>bigbear Notepad Application Login </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>
<body>
<div class= "Note-title" >bigbear Notepad application Login </div>
<form action= "/login" method= "POST" >
<span> User name: </span><input type= "text" name= "name"/><br/><br/>
<span> Password: </span><input type= "password" name= "password"/>
<input type= "Submit" value= "Login"/>
<a href= "reg.html" > I want to register </a>
</form>
</body>

Effect Chart:

(2), set up the user registration page, the code is as follows:

Copy Code code as follows:

<!doctype html>
<title>bigbear Notepad Application Registration </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>
<body>
<div class= "Note-title" >bigbear Notepad application registration </div>
<form action= "/reg" method= "POST" >
<span> User name: </span><input type= "text" name= "name"/><br/><br/>
<span> Password: </span><input type= "password" name= "password"/><br/><br/>
<input type= "Submit" value= "registered"/>
</form>
</body>

Effect Chart:

(3), establish "Mongodb" connection code, as follows:

Copy Code code as follows:

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), establish the Model entity class "User", as follows:

Copy Code code as follows:

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 ({//Determine if this user exists
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;

Effect Chart:

(5), set up the application "app", as follows:

Copy Code code as follows:

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.");
}) ;

Explain:

(1) "Connect.query ()"------Handle "get" request parameter resolution.

(2) "Connect.bodyparser ()"------Process the "Post" request parameter resolution.

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

Represents the template view "HTML" and the resource directory for static resources such as "Js,css,jpg,gif", respectively.

The following is the directory structure for this application:

Four, sum up

(1), grasps the Nodejs Operation Database Basic Operation statement.

(2), dividing levels, such as models, views, routes.

(3), constantly optimize and modify the examples of this article (such as registration to verify the existence of users, can be independent of "Usermanager" to do a layer of agents to complete user verification and save the action).

(4), tomorrow continue to complete the follow-up function, please look forward to.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.