Home>

express:?web application framework for?node.js?express is a simple and flexible node.js web application development framework, It provides a series of powerful features,Help you create a variety of web and mobile applications.

table of Contents

This article focuses on the development framework of express4.x (specifically 4.10.4).Which will also involve related content such as mongoose, ejs, bootstrap.

Build project

Directory Structure

express4.x configuration file

ejs template use

bootstrap interface framework

Routing function

session use

Page tips

Page access control

Development environment:

ubuntu

monogodb:v2.6.4

nodejs:v0.11.2

npm 2.1.10 (if nodejs is installed at version 1.2.19, this article is upgraded to version 2.x)

Build project

Enter the project directory

mkdir workplace

cd workplace

Install express globally. Express is installed as a command on the system.

npm install -g express

View the express version

express -v

Note:The express command is no longer included in the express4.x version.

Need to install express-generator

npm install express-generator -g

For detailed installation process, please refer to "Preparing Nodejs Development Environment for Ubuntu"

Use the express command to create the project,And support ejs

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 (routes directory,In the future, programs will be developed in this directory.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 files, etc.)

create:nodejs-demo/views/index.ejs

create:nodejs-demo/views/error.ejs

create:nodejs-demo/bin

create:nodejs-demo/bin/www (startup file,For starting app.js)

install dependencies:

$cd nodejs-demo &&npm install

run the app:

$debug=nodejs-demo ./bin/www

The project was created successfully.

Follow the above prompts to install dependencies:

cd nodejs-demo &&npm install

Follow the prompts to launch the web:

$debug=nodejs-demo ./bin/www

However, we do not intend to use this method to start the program.The reason is that we need to use a tool like nodemon during the development process.

nodemon is used to dynamically identify project changes during development,Then load it dynamically (this is similar to eclipse development java web). This tool is necessary for web development

Install nodemon:

npm install nodemon -g

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

The reason is that nodemon ./bin/www has no way to identify changes to the project.(My personal experiment,If there is a known Daniel,Hope to enlighten me)

Modify app.js:

Comment out the last line //module.exports=app;

Replaced by:app.listen (3000);

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

Then modify the program,See if it loads dynamically.There will be the following prompt:

1 dec 16:22:07 – [nodemon] restarting due to changes ...

1 dec 16:22:07 – [nodemon] starting `node app.js`

It takes effect.

test:

The local 3000 port is opened,Access via browser:localhost:3000

Directory structure

./

drwxrwxr-x 5 hadoop hadoop 4096 Dec 1 15:57 ../

-rw-rw-r– 1 hadoop hadoop 1495 Dec 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 Dec 1 15:57 bin /

drwxrwxr-x 9 hadoop hadoop 4096 Dec 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 Dec 1 15:57 public /

drwxr-xr-x 2 hadoop hadoop 4096 Dec 1 15:57 routes /

drwxr-xr-x 2 hadoop hadoop 4096 Dec 1 15:57 views /

Directory introduction:

node_modules, which stores all project dependencies.(Each project manages its own dependencies,(Different from maven, gradle, etc.)

package.json, project dependency configuration and developer information

app.js, the main entrance to the program

public, static files (css, js, img)

routes, routing file (c, controller in mvc)

views, page file (ejs template)

nodejs-demo/bin/www (startup file,For starting app.js)

Open app.js to view the content:

/**
* Module dependencies
* /
var express=require ("express")
, routes=require ("./routes")
, user=require ("./routes/user")
, http=require ("http")
, path=require ("path");
var app=express ();
//Environment variables
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);
//start and port
http.createserver (app) .listen (app.get ("port"), function () {
console.log ("express server listening on port" + app.get ("port"));
});

4. ejs template use

Make ejs template file,Use a file with the html extension.

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

Rename:views/*. Ejs to views/*. Html

Access to localhost:3000 is correct

Mainly rename files such as index.ejs

5. Add bootstrap interface framework

In fact, copy the js, css files to the corresponding directory in the project. 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 split the index.html page into 3 sections:header.html, index.html, footer.html

header.html, for the header area of ​​the html page

index.html, display area for content

footer.html, the bottom area of ​​the page

header.html

<! Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><%=:title%></title>
<!-Bootstrap->
<Link href="http://www.geedoo.info/stylesheets/bootstrap.min.css" rel="stylesheet" media="screen">
<!-<Link href="http://www.geedoo.info/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">->
</head>
<body screen_capture_injected="true">
index.html
<%include header.html%>
<h1><%= title%></h1>
<p>welcome to<%= title%></p>
<%include footer.html%>
footer.html
<script src="http://www.geedoo.info/javascripts/jquery-1.9.1.min.js"<&/script>
<script src="http://www.geedoo.info/javascripts/bootstrap.min.js"></script>
</body>
</html>

Accessing localhost:3000 is correct.

We have successfully used the function of ejs template,Separate the common head and bottom from the page.

And bootstrap interface framework has been introduced.

6. Routing function

Let's design the user login business requirements.

Access path:/, page:index.html, no login required,Can be accessed directly.

Access path:/home, page:home.html, users must log in,To be accessible.

Access path:/login, page:login.html, landing page,The username and password are entered correctly.Automatically jump to home.html

Access path:/logout, Page:None, after logging out,Automatically return to the index.html page

Open the app.js file and add 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 is a get request, post is a post request, all is all requests for this path

We open the routes/index.js file and add the corresponding methods.

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

login.html

<%include header.html%>
<div>
<form method="post">
<fieldset>
<legend>User Login</legend>
<div>
<label for="username">username</label>
<div>
<input type="text" name="username">
</div>
</div>
<div>
<label for="password">password</label>
<div>
<input type="password" name="password">
</div>
</div>
<div>
<button type="submit">login</button>
</div>
</fieldset>
</form>
</div>
<%include footer.html%>
home.html:
<%include header.html%>
<h1>welcome<%= user.username%> ;, welcome to login! !!</h1>
<a claa="btn" href="http://www.geedoo.info/logout">Exit</a>
<%include footer.html%>

Modify index.html, add landing link

index.html

<%include header.html%>
<h1>welcome to<%= title%></h1>
<p><a href="http://www.geedoo.info/login">Login</a></p>
<%include footer.html%>

We have written the routing and the page.Go and try it on the website.

7. session use

From the example just came,When executing exports.dologin, if the username and password are correct,The home we jumped to using the redirect method

res.redirect ("/home");

When export.home is executed, 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 the user object be assigned to the session when dologin, each page no longer passes a value.

session this problem,In fact, it involves the underlying processing of the server.

A web server like Java is a multi-threaded call model.Each user request opens a thread,Each thread maintains the state of the user in the content.

A web server like PHP is handled by the Bank of Communications cgi program.cgi is stateless,So generally use the cookie in the customer's browser to maintain the state of the user.But the information the cookie maintains on the client is not enough,Therefore, to simulate a user session in a cgi application, a session file needs to be generated and stored on the server.Let the original stateless cgi application, through the way of intermediate files,Reach the effect of the session.

The nodejs web server is also a stateless cgi program.The difference from php is thatSingle-threaded applications,All requests are responded asynchronously,Data is returned via callback.If we want to save session data, we also need to find a store.Via file storage,Redis, mongdb are fine.

Next, I will demonstrate how to save the session through mongodb and implement user object transfer after login.

app.js file

Add the following code in the appropriate places:

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 (session ({
 secret:"test.com", store:store, cookie:{maxage:10000} //expire session in 10 seconds
}));
//Used to set the login user to res.locals and display it in home.html
app.use (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.

Session-mongoose is used to connect to the mongodb database. Then automatically write the session information to the database (you can also use mongoose middleware, but you need to implement session writing yourself)

app.use (session (….)) Here is how the session information and session information storage are set globally.

Note:The app.js file has order requirements.Be sure to pay attention! !! !!

Install the session-mongoose dependency library

npm install connect

npm install session-mongoose

npm install session-mongoose

There were errors in the installation but that's okay.

Access :, normal

Modify the routes/index.js file

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

At this time the session is already working,The users of exports.home show that the passed value has been removed. It is assigned by the framework through the res.locals variable of app.use in app.js.

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

Note:This session is written in express4.10.4, which is different from the previous version of express4.

Visit the page to see if mongodb has data:

nodejs-mongodb

nodejs-mongodb

Because of the cookie configured above:(maxage:10000) //expire session in 10 seconds

expire date,So you will see that the data in mongodb is cleared after a while.

mongoose:

About the difference between express4.2.0 and express3.x operation:

8. Page prompt

We have finished the landing,Finally, let's take a look at the login failure.

We hope that if a user logs in,The username or password is wrong.Will prompt the user,How should it be achieved.

Open app.js and add res.locals.message

We have finished the landing,Finally, let's take a look at the login failure.

We hope that if a user logs in,The username or password is wrong.Will prompt the user,How should it be achieved.

Open app.js and 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>" + err + "</div>";
 next ();
});

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

<%include header.html%>
<div>
<form method="post">
<fieldset>
<legend>User Login</legend>
<%-message%>
<div>
<label for="username">username</label>
<div>
<input type="text" name="username" value="admin">
</div>
</div>
<div>
<label for="password">password</label>
<div>
<input type="password" name="password" value="admin">
</div>
</div>
<div>
<button type="submit">login</button>
</div>
</fieldset>
</form>
</div>
<%include footer.html%>

Modify routes/index.js and add 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="The username or password is incorrect";
 return res.redirect ("/login");
 }
};

Let's see the effect:enter the wrong and password, Username:dad, password:da

boostrap-nodejs

9. Page access control

The landing part of the website has been completed according to our requirements,But the website is not secure.

localhost:3000/home, the page was originally accessed after login,Now we don't log in,It is also accessible by typing directly into the browser.

The page is wrong.Prompt<%= user.username%>variable error.

get/home?user == a 500 15ms

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

1 |<%include header.html%>

>>2 |<h1>welcome<%= user.username%> ;, welcome to login! !!</h1>

3 |<a claa="btn" href="">Exit</a>

4 |<%include header.html%>

cannot read property "username" of null

at eval (eval at(d:\ workspace \ project \ nodejs-demo \ node_modules \ ejs \ lib \ ejs.js:

at eval (eval at(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 opened and posted,Because there is no user.username parameter. We avoid such errors.

Also record the role of get, post, all mentioned in the routing section?I'm going back to the routing configuration now,Do something more.

Modify the app.js file

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:

/, Anyone can visit,No control

/login, use all to intercept all requests for access to/login, first call authentication, user login check

/logout, use get to intercept the request to access/login, first call notauthentication, the user does not log in to check

/home, use get to intercept the request to access/home, first call authentication, user login check

Modify the app.js file to add authentication and notauthentication

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="Signed in";
  return res.redirect ("/home");
 }
 next ();
}

After configuration,We are not logged in,When you visit localhost:3000/home or localhost:3000/logout directly, you will jump to the/login page.

After login, visit localhost:3000/login and jump directly to the/home page

So far, the content related to express4 ends here.

The above is a handy note of the nodejs express4.x development framework that we share with you,Hope you like it.

  • Previous Nodejs primary stage express
  • Next Interpreting ASPNET 5&MVC6 Series Tutorials (3): Project Release and Deployment