Nodejs express4.x Development Framework Handy notes _node.js

Source: Internet
Author: User
Tags anonymous button type eval generator mongodb php web server java web

Express:? Web application Framework for? Node.js? Express is a concise, flexible node.js Web application Development framework that provides a wide range of features to help you create Web and mobile device applications.

Directory

This paper focuses on the development framework of express4.x (specifically 4.10.4), which also involves mongoose,ejs,bootstrap and other related content.

Establish engineering
Directory structure
express4.x configuration file
Ejs Template Use
Bootstrap interface Frame
Routing Features
Session use
Page Tips
Page access Control

Development environment:

Ubuntu

monogodb:v2.6.4

nodejs:v0.11.2

NPM 2.1.10 (1.2.19 If Nodejs is installed, this article is upgraded to the 2.x version)

1. Establishment of the project

Access to the Engineering directory

mkdir Workplace

CD Workplace

The global install express,express is installed in the system as a command.

NPM Install-g Express

View Express version

Express-v

Note: Express commands are not included in the express4.x version.

Need to install Express-generator

NPM Install Express-generator-g

Detailed installation process see: "Prepare Nodejs development environment Ubuntu"

Create a project with express command and support Ejs

hadoop@sven:~/workspace/nodejs$ express-e Nodejs-demo

Create:nodejs-demo (project name)
Create:nodejs-demo/package.json (Project package information)
Create:nodejs-demo/app.js (main program)
Create:nodejs-demo/public (Public directory)
Create:nodejs-demo/public/images
Create:nodejs-demo/public/javascripts
Create:nodejs-demo/public/stylesheets
Create:nodejs-demo/public/stylesheets/style.css
Create:nodejs-demo/routes (Routing directory, later in this directory to develop the program, and then use in app.js)
Create:nodejs-demo/routes/index.js
Create:nodejs-demo/routes/users.js
Create:nodejs-demo/views (view directory, view template file, etc.)
Create:nodejs-demo/views/index.ejs
Create:nodejs-demo/views/error.ejs
Create:nodejs-demo/bin
Create:nodejs-demo/bin/www (boot file, used to start app.js)
Install dependencies:
$ cd Nodejs-demo && NPM Install
Run the app:
$ debug=nodejs-demo./bin/www

Project creation succeeded.

Install dependencies based on the above prompts:

Copy Code code as follows:

CD Nodejs-demo && NPM Install

To start the web as prompted:

Copy Code code as follows:

$ debug=nodejs-demo./bin/www

But we're not going to use this method to start the program here. The reason is that we need to use Nodemon as a tool in the development process.
Nodemon is used to dynamically identify project changes during development, and then dynamically load (this is the Eclipse species Development Java web similar). This tool is necessary to develop the web

Install Nodemon:

NPM Install Nodemon-g

So why don't we use the./bin/www script above?

The reason is Nodemon./bin/www This is no way to identify changes to the project. (My personal experiment, if you know Daniel, Wang Enlighten)

Modify App.js:

Put the most line//module.exports = app; note out

Replaced by: App.listen (3000);

Use the following command to start the App.js main program:

hadoop@sven:~/workspace/nodejs/nodejs-demo$ Nodemon App.js

Then modify the program to see if it will load dynamically. will have the following tips:

1 Dec 16:22:07–[nodemon] Restarting due to changes ...
1 Dec 16:22:07–[nodemon] starting ' node App.js '

Represents the entry into force.

Test:

The local 3000 port is opened and accessed through the browser: localhost:3000

2. Directory structure

./
Drwxrwxr-x 5 Hadoop Hadoop 4096 December 1 15:57. /
-rw-rw-r–1 Hadoop Hadoop 1495 December 1 16:22 app.js
-rw-r–r–1 Hadoop Hadoop 12288 December 1 16:22 app.js.swp
Drwxr-xr-x 2 Hadoop hadoop 4096 December 1 15:57 bin/
Drwxrwxr-x 9 Hadoop hadoop 4096 December 1 15:58 node_modules/
-rw-rw-r–1 Hadoop Hadoop 326 December 1 15:57 Package.json
Drwxr-xr-x 5 Hadoop Hadoop 4096 December 1 15:57 public/
Drwxr-xr-x 2 Hadoop hadoop 4096 December 1 15:57 routes/
Drwxr-xr-x 2 Hadoop hadoop 4096 December 1 15:57 views/

Directory Introduction:

Node_modules, store all the project dependencies. (each project manages its own dependencies, unlike Maven,gradle, etc.)
Package.json, Project dependency configuration and developer information
App.js, program main entrance
Public, static file (css,js,img)
Routes, routing files (C,controller in MVC)
Views, paging file (ejs template)
Nodejs-demo/bin/www (boot file, used to start app.js)

Open app.js View content:

/**
* Module Dependent * *
var express = require (' Express ')
, routes = require ('./routes ')
, user = require ('./ Routes/user ')
, http = require (' http ')
, Path = require (' path ');
var app = Express ();
environment variable
app.set (' Port ', Process.env.PORT | | 3000);
App.set (' views ', __dirname + '/views ');
App.set (' View engine ', ' Ejs ');
App.use (Express.favicon ());
App.use (Express.logger (' dev '));
App.use (Express.bodyparser ());
App.use (Express.methodoverride ());
App.use (app.router);
App.use (Express.static (Path.join (__dirname, ' public '));
Development mode
if (' development ' = = App.get (' env ')) {
app.use (Express.errorhandler ());
}
Path resolution
App.get ('/', routes.index);
App.get ('/users ', user.list);
Startup and Port
http.createserver (APP). Listen (App.get (' Port '), function () {
console.log (' Express server Listening on port ' + app.get (' Port ');
});

4. Ejs Template Use

Let the Ejs template file use the file with the extension HTML.

Modification: App.js

var Ejs = require (' Ejs '); Introduce Ejs. Reinstall Dependencies >
App.engine ('. html ', ejs.__express);
App.set (' View engine ', ' html '); App.set (' View engine ', ' Ejs ');
Renaming: Views/*.ejs for views/*.html

Access localhost:3000 Correct

Main to rename files such as Index.ejs

5. Increase the Bootstrap interface frame

In fact, the Js,css file is copied to the project in the directory. Includes 4 files:

Copy to Public/stylesheets directory

Bootstrap.min.css
Bootstrap-responsive.min.css

Copy to public/javascripts directory

Bootstrap.min.js
Jquery-1.9.1.min.js

Next, we cut the index.html page into 3 parts: header.html, index.html, footer.html

Header.html, for the head area of the HTML page
index.html, display area for content
Footer.html, for the bottom area of the page

Header.html

<! DOCTYPE html>
 
 

Access localhost:3000 correct.

We have successfully used the function of the Ejs template to separate the public head and bottom from the page.

And the Bootstrap interface framework has been introduced.

6. Routing function

We designed the user login business requirements.

Access path:/, page: index.html, do not need to login, you can access directly.
Access path:/home, page: home.html, must be logged in before the user can access.
Access path:/login, page: login.html, login page, username password entered correctly, automatically jump to home.html
Access path:/logout, page: No, after exiting login, automatically return to index.html page

Open the App.js file to increase routing configuration

App.get ('/', routes.index);
App.route ('/login ')
. Get (Routes.login)
post (routes.dologin);
App.get ('/logout ', routes.logout);
App.get ('/home ', routes.home);

Note: Get for GET request, post as POST request, all for all requests against this path

We open the Routes/index.js file and add the corresponding method.

Exports.index=function (req, res) {
 res.render (' index ', {title: ' Index '});
Exports.login=function (req,res) {
 res.render (' login ', {title: ' User Login '});
Exports.dologin=function (req,res) {
 var user = {
 username: "Admin",
 Password: "admin"
}
if ( Req.body.username==user.username && req.body.password==user.password) {
 res.redirect ('/home ');
}
Res.redirect ('/login ');
};
Exports.logout = function (req,res) {
 res.redirect ('/');
};
Exports.home = function (req,res) {
 var user = {
 username: ' admin ',
 password: ' admin '
 }
 Res.render (' home ', {title: ' Home ', User:user});

Create views/login.html and views/home.html two files

Login.html

&lt;% include header.html%&gt; &lt;div class= "Container-fluid" &gt; &lt;form class= "form-horizontal" method= "POST" &gt; &lt;fieldset&gt; &lt;legend&gt; User Login &lt;/legend&gt; &lt;div class= "Control-group" &gt; &lt;label class= "Control-label "for=" username &gt; Username &lt;/label&gt; &lt;div class= "Controls" &gt; &lt;input type= "text" class= "Input-xlarge" id= " Username "name=" username "&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=" Control-group "&gt; &lt;label class=" Control-label "for=" password "&gt; Password &lt;/label&gt; &lt;div class=" Controls "&gt; &lt;input type=" password "class=" Input-xlarge "id=" password "name=" password "&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=" Form-actions "&gt; &lt;button
Type= "Submit" class= "btn btn-primary" &gt; Login &lt;/button&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/div&gt; &lt;% include footer.html%&gt; home.html: &lt;% include header.html%&gt; &lt;h1&gt;welcome &lt;%=, User.username%&gt; Welcome to the Landing!! &lt;/h1&gt; &lt;a claa= "btn" href= "Http://www.geedoo.info/logout" &gt;Exit &lt;/a&gt; &lt;% include footer.html%&gt; 

Modify index.html, add login links

Index.html

<% include header.html%>
 
 

Routing and page We have written, go to the website to try it.

7. Session Use

From the example above, when performing exports.dologin, if the username and password are correct, we use the redirect method to jump to the home

Res.redirect ('/home ');

When we execute exports.home, we use render to render the page and pass the user object to the home.html page

Res.render (' home ', {title: ' Home ', user:user});

Why can't you assign a user object to the session when Dologin, and each page will no longer be worth it.

Session This problem, in fact, involves the bottom of the server processing methods.

Like a Java Web server, a multithreaded invocation model. Each user request opens a thread that maintains the user's state in the content.

Like the PHP Web server, is a turnkey CGI program processing, CGI is stateless, so generally use cookies in the client's browser is to maintain the user's state. But cookies in the client maintenance information is not enough, so the CGI application to imitate the user session, you need to generate a session file on the server to store, so that the original state of the CGI application, through the intermediate file way, to achieve the effect of the session.

Nodejs's Web server, also a CGI program stateless, differs from PHP in that a single-threaded application, where all requests are asynchronous responses, return data in a callback manner. If we want to save the session data, we also need to find a store that can be redis,mongdb by file storage.

Next, I'll show you how to save the session through MongoDB and implement the user object transfer after the login.

App.js file

Add the following code to the appropriate location:

var session = require (' express-session ');
var connect = require (' Connect ');
var Sessionstore = require ("Session-mongoose") (connect);
var store = new Sessionstore ({
URL: "Mongodb://localhost/session",
 interval:120000
});
App.use ({
 secret: ' test.com ',
 store:store,
 cookie:{maxage:10000}//expire
}));
Used to set the login user to the res.locals and display the App.use in home.html
(function (req,res,next) {
 Res.locals.user = Req.session.user;
 Console.log (' Session is = ', req.session.user);
 Next ();
});

Need to add middleware Connect, session-mongoose.

Where Session-mongoose is used to connect the MongoDB database. Then automatically writes session information to the database (can also use mongoose middleware, but to implement the session's write yourself)

App.use (Session (...)) Here is a global set of Session information and session information storage mode.

Note: App.js documents have order requirements, must pay attention to!!!

Installing Session-mongoose dependent libraries

NPM Install Connect

NPM Install Session-mongoose

NPM Install Session-mongoose

There are errors in the installation but it doesn't matter.

Visit: Http://localhost:3000/login, normal

modifying routes/index.js files

Exports.dologin method

Exports.dologin = function (req, res) {
 var user={username: ' admin ', Password: ' admin '} 
 if (req.body.username=== User.username && req.body.password===user.password) { 
  req.session.user=user; 
  Return Res.redirect ('/home ');
 } else {return 
  res.redirect ('/login '); 
 }
;

Exports.logout method

Exports.logout = function (req, res) {
 req.session.user=null;
 Res.redirect ('/');

Exports.home method

Exports.home = function (req, res) {
 res.render (' home ', {title: ' Home '});

This time the session has worked, Exports.home's user display value has been removed. Is the assignment made through the framework through the res.locals variable of the app.use in App.js.

App.use (function (req, res, next) {
 res.locals.user = Req.session.user;
 Next ();
});

Note: This session is written by express4.10.4 and is not the same as the previous version of EXPRESS4.

Visit the page to see if MongoDB has any data:

Nodejs-mongodb
Nodejs-mongodb

Due to the above configured cookie:{maxage:10000}//expire session in seconds
Expiration time, so you will see that the data inside the MongoDB is cleared over a period of time.
Reference:

mongoose:http://mongoosejs.com/

About the difference between express4.2.0 and express3.x operations: http://blog.csdn.net/u013758116/article/details/38758351

8. Page Tips

Landing on the general we have finished, and finally look at the failure of landing.

We hope that if the user login, user name or password error, will give users a hint, how to achieve.

Open App.js, add res.locals.message

Landing on the general we have finished, and finally look at the failure of landing.

We hope that if the user login, user name or password error, will give users a hint, how to achieve.

Open App.js, add res.locals.message

App.use (function (req, res, next) {
 res.locals.user = Req.session.user;
 var err = Req.session.error;
 Delete Req.session.error;
 Res.locals.message = ';
 if (err) res.locals.message = ' <div class= ' alert Alert-danger ' > ' + err + ' </div> ';
 Next ();
});

Modify Login.html page, <%-message%>

<% include header.html%>
<div class= "Container-fluid" >
<form class= "Form-horizontal" method= "POST" >
<fieldset>
<legend> User Login </legend>
<%-message%>
<div class= "Control-group" >
<label class= "Control-label" for= "username" > Username </label>
<div class= " Controls ">
<input type=" text class= "Input-xlarge" id= "username" name= "username" value= "admin" >
</div>
</div>
<div class= "Control-group" >
<label class= "Control-label" for= " Password "> Password </label>
<div class=" Controls "> <input type=" password "class="
Input-xlarge "id=" password "name=" password "value=" admin ">
</div>
</div>
<div class= "Form-actions" >
<button type= "Submit" class= "BTN btn-primary" > Landing </button>
</div >
</fieldset>
</form>
</div>
<% include footer.html%>

Modify Routes/index.js to increase Req.session.error

Exports.dologin = function (req, res) {
 var user={
 username: ' admin ',
 password: ' admin '
 }
 if ( Req.body.username===user.username && req.body.password===user.password) {
 req.session.user=user;
 Return Res.redirect ('/home ');
 } else {
 req.session.error= ' username or password is incorrect ';
 Return Res.redirect ('/login ');
 }
;

Let's see the effect: Http://localhost:3000/login entered the wrong and password, username: Dad, password: DA

Boostrap-nodejs

9. Page access Control

Site landing part According to our request has been completed, but the site is not safe.

Localhost:3000/home, the page was originally landed after the visit, now we do not login, directly in the browser input can also be accessed.

Page error, prompt <%= user.username%> variable error.

Get/home?user==a 15ms


Typeerror:d:\workspace\project\nodejs-demo\views\home.html:2


1| &lt;% include header.html%&gt;


&gt;&gt; 2| &lt;h1&gt;welcome &lt;%= User.username%&gt, Welcome to the landing!! &lt;/h1&gt;


3| &lt;a claa= "btn" href= "Http://www.geedoo.info/logout" &gt; Exit &lt;/a&gt;


4| &lt;% include header.html%&gt;


Cannot read property ' username ' of NULL


At Eval (eval at &lt;anonymous&gt; (D:\workspace\project\nodejs-demo\node_modules\ejs\lib\ejs.js:


At Eval (eval at &lt;anonymous&gt; (D:\workspace\project\nodejs-demo\node_modules\ejs\lib\ejs.js:


At d:\workspace\project\nodejs-demo\node_modules\ejs\lib\ejs.js:249:15


At Object.exports.render (d:\workspace\project\nodejs-demo\node_modules\ejs\lib\ejs.js:287:


At View.exports.renderFile [as engine] (D:\workspace\project\nodejs-demo\node_modules\ejs\l


At View.render (D:\workspace\project\nodejs-demo\node_modules\express\lib\view.js:75:8)


At Function.app.render (D:\workspace\project\nodejs-demo\node_modules\express\lib\applicati


At ServerResponse.res.render (D:\workspace\project\nodejs-demo\node_modules\express\lib\res


At Exports.home (D:\workspace\project\nodejs-demo\routes\index.js:36:8)


At Callbacks (d:\workspace\project\nodejs-demo\node_modules\express\lib\router\index.js:161

This page was developed because there are no user.username parameters. We avoid such a mistake happening.

Also record the role of Get,post,all in the routing section? Now I'm going to go back to the routing configuration and do something.

modifying app.js files

App.get ('/', routes.index);
App.route ('/login ')
. All (Notauthentication)
. Get (Routes.login)
. Post (Routes.dologin);
App.route ('/logout ')
App.get ('/', routes.index);
App.route ('/login ')
. All (Notauthentication)
. Get (Routes.login)
. Post (Routes.dologin);
App.route ('/logout ')
. Get (authentication)
. get (Routes.logout);
App.route ('/home ')
. Get (authentication)
. get (Routes.home);

Access control:

/, who visits all lines, without any control
/login, use all to intercept all Access/login requests, first call authentication, user login check
/logout, use Get intercept access/login request, first call notauthentication, user does not log in check
/home, use Get intercept access/home request, first call authentication, user login check
Modify App.js file, add authentication,notauthentication two methods

function authentication (req, res, next) {
 if (!req.session.user) {
 req.session.error= ' please login first ';
 Return Res.redirect ('/login ');
 }
 Next ();
}
function Notauthentication (req, res, next) {
 if (req.session.user) {
  req.session.error= ' landed ';
  Return Res.redirect ('/home ');
 }
 Next ();
}

After the configuration, we do not login, direct access to Localhost:3000/home or Localhost:3000/logout, will jump to the/login page

Once logged in, the access Localhost:3000/login jumps to the/home page directly

Here, EXPRESS4 related content ends here.

The above content is small to share the Nodejs express4.x Development Framework Handy notes, I hope you like.

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.