Node JS Web Development Simple Demo Learning notes __js

Source: Internet
Author: User


I started in January this year to contact node JS, contact the time is not long, so the technical level has yet to be improved, I hope this simple article can help you learn Nodejs.

I. Description of the project

1. Project Summary:

The main use of Nodejs to achieve a basic demo of the additions and deletions of the function of the Nodejs technology in the expansion of the development of the project preparation. The development environment mainly uses the Webstorm, the database uses the MySQL, uses the Nodejs Express. A Nodejs MySQL expansion pack was invoked. A Nodejs Node-uuid expansion pack was invoked, primarily for the creation of the UUID. Called the Nodejs Async expansion pack, which is used primarily for sorting processing of callback functions.

The page template mainly uses Ejs, but changes the suffix name to HTML in concrete use.

2. Project structure:

Bin directory: Www.js file. The development environment is created automatically when the project is created and can be used to modify the default access address.

DAO Directory: A collection of tools about database-related operations.

Config.js: Database registration information.

Daobase: A tool for Database basic DQL and DML operations.

Userdao: A tool class for modifying the function of the Tb_test_user_ table.

Model directory: Project data models.

User: Data model.

Node_modules: The project-related library files added by the development environment.

Public: (not used)

Routes:nodejs the control layer of express package, the function of routing selector. Used to assign access paths.

Index.js: The realization of basic page background logic function
Users.js: (not used)

Test: Customizing the testing Package

Asynctest.js: For testing the Async component (test function available but the actual function is problematic, leave it for future research points)

Test.js: Test for the daobase.js function.

Testdao.js: A test for userdao.js functionality.

Views:ejs Template Page Collection

Error.html: Used to display error messages

Index.html: Login Page

insert.html: Adding pages

Success.html: Used to display all the data, the successful jump page after the function

update.html: Modifying the page

App.js: Routing mapping Table (mainly used for jump logic under routes, this file is mainly used for mapping selection)

Package.json: Similar to Mavon pom.xml, mainly used for dependent package version registration

3. Database Design Details

Database name: Db_test_

Table Name: Tb_test_user_

Column name: ID data type: varchar default length: 50 Other: Primary key

Column Name: Name data type: varchar default length: 50 Other: None

Column Name: password data type: varchar default length: 50 Other: None

Second, the detailed implementation

1, www.js documents

Introducing App.js Files

var app = require ('.. /app ');

2, Config.js documents

module.exports={
Host: ' localhost ',
User: ' Root ',
Password: ' Root ',
Database: ' Db_test_ ',
ports:3306
};

Detailed

Module.exports refers to exposing a file to the module space, while the file represents the current function. (This file function is in JSON format). Host: The url,user,password,database,ports for MySQL is: The account number, password, database name and port number of the database that needs to be used.

3, Daobase.js documents

var config=require ('./config.js ');//Introducing configuration file
var mysql=require (' MySQL ');//introduction of MySQL Driver
var pool=mysql.createpool (config);//CREATE Database connection pool
DQL function (function for query)
Exports.executequery=function (SQL, data, callback) {

Create the connection and set the relevant action within its callback function (Nodejs related operations are in the callback function, the problem is larger, the code complexity increased)
Pool.getconnection (function (err,conn) {
if (err) {
Callback (Err,null,null);
}else{

/* is different from the DML callback function parameter table, other similar

Qerr: Returns NULL when correct, returns useful value when error

Vals: For storing return value information, returns an array of objects, with the following table plus the column name of the table to obtain the value, examples are as follows: Vals[0].name

Fields: Returns information about the structure of the table. (I do not use it)
*/

Conn.query (Sql,data,function (Qerr, Vals, fields) {

Resetting a database connection
Conn.release ();

//For incoming callback functions, processing data
                 callback (Qerr,vals,fields);
            });
        }
    });
};
//dml function (functions for adding, modifying, deleting)
Exports.executeupdate = function (sql, data, callback)  {
    pool.getconnection function (err, conn)  {
         if  (Err)  {
             callback (Err, null, null);
        } else {

Data is used for placeholders, some unexpected cases I haven't tested
Conn.query (SQL, data, function (Qerr, result) {
Release connection
Conn.release ();
Event-driven callbacks
Callback (qerr, result);
});
}
});
};

4, Userdao.js documents

var daobase = require ('./daobase ');//Introducing Dbutil
var uuid = require (' Node-uuid ');//introduction of UUID Module
var user_db = require ('.. /model/user ');//Introducing model modules
var UserDB = new user_db ()//Instantiation Model module
Add user
Exports. Insertuser=function (params, callback) {
The Var data=[];//is poorly written and should be modeled after the instantiation, but does not affect the use of the
var sql= ' INSERT into Tb_test_user_ (Id,name,password) VALUES (?,?,?) ';
var id=uuid.v4 ();
Data.push (ID);//Add array in placeholder order
Data.push (Params.name);
Data.push (Params.password);
Daobase.executeupdate (Sql,data,callback);
};
Modify User
Exports. Updateuser=function (Params,id, callback) {
var sql= ' UPDATE tb_test_user_ SET name=?,password=? WHERE id=? ';
var data=[];
Data.push (Params.name);
Data.push (Params.password);
Data.push (ID);
Daobase.executeupdate (Sql,data,callback);
};
Delete User
Exports. Deleteuser=function (Id,callback) {
var sql= ' Delete from Tb_test_user_ where id=? ';
var data=[];
Data.push (ID);
Daobase.executeupdate (Sql,data,callback);
};
Query All Users
Exports. Findall=function (callback) {
var sql= ' select * from Tb_test_user_ ';
Daobase.executequery (Sql,callback);
};
Query by ID
Exports. Findbyid=function (Id,callback) {
var sql= ' select * from Tb_test_user_ where id=? ';
var data=[];
Data.push (ID);
Daobase.executequery (Sql,data,callback);
};
Login Verification
Exports. Userlogin=function (Params,callback) {
var sql= ' select * from Tb_test_user_ where name=? and password=? ';
var data=[];
Data.push (Params.name);
Data.push (Params.password);
Daobase.executequery (Sql,data,callback);
}

5, User.js documents

Module.exports=user;
function User () {
This.tablename= ' Tb_test_user_ ';
this.id= ' id ';
This.name= ' name ';
this.password= ' password ';
}

6, Index.js documents

var express = require (' Express ');//introduction of Express Package
var userdao=require ('.. /dao/userdao.js ');//introduction of Userdao File
var user_db = require ('.. /model/user ');//Introducing the User entity

Modify Initialization
Exports.update=function (req,res) {
The get-obtain-access method for Var Id=req.query.id;//nodejs uses req.query. Parameter names
Console.log (ID);
Userdao.findbyid (Id,function (Qerr, Vals,fields) {
if (!) ( Qerr==null)) {

Select Render Ejs template and jump to pass
Res.render (' Error ', {
Message: ' Find modify element failed '
});
}

Get the information inside the database and upload it to the page (note that multiple callback function nesting is used here)
var username=vals[0].name;
var Password=vals[0].password;
var id=vals[0].id;
Res.render (' Update ', {
Title: ' Modify Data ',
Username:username,
Password:password,
Id:id
});
});
};
Modify (initial chemical for modifying the page)
Exports.doupdate=function (req,res) {
var id=req.body.id;//post receives the way req the value. Body. Parameter name (required for post transfer)
var name=req.body.username;
var Password=req.body.password;
var user=new user_db ();
User.name=name;
User.password=password;
Userdao.updateuser (User,id,function (qerr, result) {
if (!) ( Qerr==null)) {
Res.render (' Error ', {
Message: ' Modify failed '
});
}

Determines whether a DML operation succeeds with the number of rows affected (note that the function does not return an error even if the number of rows affected is 0)
if (result.affectedrows>0) {
Console.log (' success ');
Userdao.findall (function (qerr,vals,fields) {
var result=vals;
Res.render (' success ', {
Title: ' Modify Success ',
Result:result
});
});
}
});
};
Delete
Exports.delete=function (req,res) {
var id=req.query.id;
Userdao.deleteuser (Id,function (qerr, result) {
if (!) ( Qerr==null)) {
Console.log (' error ');
Res.render (' Error ', {
Message: ' Delete failed '
});
}
if (result.affectedrows>0) {
Console.log (' success ');
Userdao.findall (function (qerr,vals,fields) {
var result=vals;
Res.render (' success ', {
Title: ' Delete Success ',
Result:result
});
});
}
});
};
Add initialization
Exports.insert=function (req,res) {
&n

Related Article

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.

Tags Index: