Study Notes -Express

Express

Basics

Understanding express

npm提供了大量的第三方模块,其中不乏许多Web框架,比如我们本章节要讲述的一个轻量级的Web框架 ——— Express。

Express is a simple, flexible node.js Web application development framework that provides a range of powerful features, such as: template parsing, static files, middleware, routing control, etc., and can also use plug-in or integrated with other modules help you create a variety of Web and mobile applications, is currently the most popular Web development framework based on Node.js, and support Ejs, jade and other templates, you can quickly build a fully functional website.
  Well, let's get started!
NPM installation
npm install express
to obtain references

var express = require('express');
var app = express();
通过变量“app”我们就可以调用express的各种方法了,好戏刚刚开始,继续加油吧!

Creating an application

认识了Express框架,我们开始创建我们的第一个express应用。

app.js add the following in our default item master file:

var express = require('express');
var app = express();
app.get('/', function (request, response) {  
   response.send('Hello World!');
});
app.listen(80);

Description: In the later course, we will be unified to use port 80 to listen for requests.
  After the addition is complete, the browser to view the contents of the "address test" right-hand column, when you see the "Hello World!" To show the contents of a simple express application has created a success.

get request

前面我们实现了一个简单的express应用,下面我们就开始具体讲述它的具体实现,首先我们先来学习Express的常用方法。

get method - according to process the request path GET request sent by the client.
  Format: app.get (path, function (request, Response));
  path is a path of the request, the second parameter is a callback function processing request, there are two parameters and Response request, on behalf of the request information and the response information.
The following example:

var express = require('express');
var app = express();
 
app.get('/', function(request, response) {
   response.send('Welcome to the homepage!');
});
app.get('/about', function(request, response) {
   response.send('Welcome to the about page!');
});
app.get("*", function(request, response) {
    response.send("404 error!");
});
app.listen(80); 

In the above example, the specified path about the page, and the processing method of the root path of all paths. And internal callback function, send method of the HTTP response, indicates to the browser to send a string.
  Referring to the above code, try to get yourself a request path, then the browser access request if the address can be successful.

Brief Middleware

Middleware <Middleware>
1. What is middleware?
Middleware (Middleware) HTTP request handler is used to perform various specific tasks, such as checking whether the user is logged, analyzed data, and other required prior to the final transmit data to the user task. Its greatest feature is that a middleware processed, the corresponding data can be then passed to the next intermediate.
2. a do nothing, middleware only pass the request object, something like this:

function Middleware(request, response, next) { 
   next();
}
上面代码的next为中间件的回调函数。如果它带有参数,则代表抛出一个错误,参数为错误文本。
function Middleware(request, response, next) { 
   next('出错了!');
}

After an error is thrown back middleware will not be executed until it finds an error-handling function so far. If you do not call the next method, function is not registered later executed.

all methods

和get函数不同app.all()函数可以匹配所有的HTTP动词,也就是说它可以过滤所有路径的请求,如果使用all函数定义中间件,那么就相当于所有请求都必须先通过此该中间件。
格式:app.all(path,function(request, response));
如下所示,我们使用all函数在请求之前设置响应头属性。
var express = require("express");
var app = express();
 
app.all("*", function(request, response, next) {
    response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });      //设置响应头属性值
    next();
});
 
app.get("/", function(request, response) {
    response.end("欢迎来到首页!");
});
 
app.get("/about", function(request, response) {
    response.end("欢迎来到about页面!");
});
 
app.get("*", function(request, response) {
    response.end("404 - 未找到!");
});
 
app.listen(80);

The above code parameter "*" represents an effective paths of all, this method is especially useful when dealing with a specific prefix to the path, or any path, whether we are requested in advance by any route all functions.
  If, if we skip all functions and what will happen, try it yourself?

use basic usage 1

use是express调用中间件的方法,它返回一个函数。
格式:app.use([path], function(request, response, next){});
可选参数path默认为"/"。
1.使用中间件

app.use(express.static(path.join(__dirname, '/')));
As yet, we use use function calls express middleware set access path static files directory (assuming that this is the root path).
2. How to call two consecutive middleware it, the following example:

var express = require('express');
var app = express();
 
app.use(function(request, response, next){
    console.log("method:"+request.method+" ==== "+"url:"+request.url);
    next();
});
 
app.use(function(request, response){
    response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
    response.end('示例:连续调用两个中间件');
});
 
app.listen(80);
回调函数的next参数,表示接受其他中间件的调用,函数体中的next(),表示将请求数据传递给下一个中间件。
上面代码先调用第一个中间件,在控制台输出一行信息,然后通过next(),调用第二个中间件,输出HTTP回应。由于第二个中间件没有调用next方法,所以req对象就不再向后传递了。

use Method 2

The method can be invoked only use the middleware, but also according to the requested URL, and returns the page content, the following example:

var express = require("express");
var app = express();

app.use(function(request, response, next) {
   if(request.url == "/") {
      response.send("Welcome to the homepage!");
   }else {
      next();
   }
});
 
app.use(function(request, response, next) {
   if(request.url == "/about") {
     response.send("Welcome to the about page!");
   }else {
     next();
   }
});
 
app.use(function(request, response) {
  response.send("404 error!");
});
app.listen(80);

By the above code request.url property, the URL request is determined, returning different content.

Callback

Express callback function takes two parameters, namely the request (referred to as req) and response (referred to as res), request sent on behalf of a client HTTP request, response sent to the client on behalf of the HTTP response, these two parameters are objects. Examples are as follows:

function(req, res) {
 
});

In the latter study, we often deal with it, keep in mind its format now!
### to get the host, pathname
today we have to learn how to use the req object to handle client to the HTTP request.
1.req.host returns the requested host name is taken in advance (the port number is not included).
2.req.path return path name of the URL request.
The following example:

var express = require('express');
var app = express();
 
app.get("*", function(req, res) {
    console.log(req.path);
    res.send("req.host获取主机名,req.path获取请求路径名!");
});
 
app.listen(80);

Try any input in the browser a request path, a request to view a host name or a path through req.

Get request - query

a query is available client object attribute get request path parameter contains the parsed request parameters object, the default for the {}.

var express = require('express');
var app = express();
 
app.get("*", function(req, res) {
    console.log(req.query.参数名);
    res.send("测试query属性!");
});
 
app.listen(80);

Get object parameter values get request path through req.query.
Format: req.query parameter name; request path following Examples:
Example 1: / search n = Lenka?

req.query.n  // "Lenka"

例2: /shoes?order=desc&shoe[color]=blue&shoe[type]=converse

req.query.order  // "desc"
 
req.query.shoe.color  // "blue"
 
req.query.shoe.type  // "converse"

Try a get request path parameters, using the "req.query. Parameter name" request parameter value acquisition method.

Get request - param

And attribute query, we can get the value is parsed request parameters object by req.param.
Format: req.param ( "parameter name"); exemplary request path follows:
? Example 1: Obtaining the parameter values requested root path, such as / n = Lenka, as follows:

var express = require('express');
var app = express();
 
app.get("/", function(req, res) {
    console.log(req.param("n")); //Lenka
    res.send("使用req.param属性获取请求根路径的参数对象值!");
});
 
app.listen(80);

Example 2: We may also obtain the requested object having a corresponding routing rules, assuming the routing rule
/ user /: name /, the request path / user / mike, as follows:

app.get("/user/:name/", function(req, res) {
    console.log(req.param("name")); //mike
    res.send("使用req.param属性获取具有路由规则的参数对象值!");
});

PS: The so-called "routing" refers to a different access path, specify a different approach.
Read the above example, try to resolve a property path using req.param object request and obtain the requested parameter values.

Get request - params

Param and similar, but can be resolved params is a complex name contains routing rules requested object attributes.
Format: req.params parameter name;
Examples Example 1 above, the request class of the root, so we can obtain as follows:

var express = require('express');
var app = express();
 
app.get("/user/:name/", function(req, res) {
    console.log(req.params.name); //mike
    res.send("使用req.params属性获取具有路由规则的参数对象值!");
});
 
app.listen(80);

View run results, and param attribute function is the same, the same name parameter acquisition value.
Example 2: Of course, we may also request complex routing rules, such as / user /: name /: id , request address is assumed: / user / mike / 123, as follows:

app.get("/user/:name/:id", function(req, res) {
    console.log(req.params.id); //"123"
    res.send("使用req.params属性复杂路由规则的参数对象值!");
});

For path request address with routing rules, the property than the params param attribute is not yet strong so a little bit of it!

send basic usage

send () method sends a response message to the browser, and intelligently handle different types of data. Format is as follows:

res.send([body|status], [body]);

1. When the argument is a String, Content-Type The default setting is "text / html".

res.send('Hello World'); //Hello World

2. When the argument is Array or Object, Express will return a JSON.

res.send({ user: 'tobi' }); //{"user":"tobi"}
res.send([1,2,3]); //[1,2,3]

3. When the argument is a Number, and no one mentioned above in the response in the body, Express will help you set up a body response, such as: 200 characters will return "OK".

res.send(200); // OK
res.send(404); // Not Found
res.send(500); // Internal Server Error

The method will automatically send some settings when the output response, information such as HEAD, HTTP cache support the like.

Prepare landing

Mounting template

From this lesson we begin to use the express framework to achieve a simple user sign-on function, let's get ready resources.
  Use express nodejs framework, which is the default rendering template ejs and jade, today we have to ejs template, for example, about the template page template rendering of basic functions.
1.ejs template installation methods

npm install ejs

2. After installing the next directory, how to call it, as follows:

//指定渲染模板文件的后缀名为ejs
app.set('view engine', 'ejs');

Ejs default template file to render support only ejs extension, it may be in use when writing code that will find its way very uncomfortable or want to use in the form of html to write, how to do it, then we have to modify the template engine , and also will use the express function of engine.
a function of engine registration template engine, process the specified file extension.

// 修改模板文件的后缀名为html
app.set( 'view engine', 'html' );
// 运行ejs模块
app.engine( '.html', require( 'ejs' ).__express );

"__Express", a public property ejs module, showing file extensions to be rendered.

Static resources

Due to environmental constraints, here we do not use static resources, but the actual development, we certainly will be used, the specific use of the rules listed below, you can reference.
If you want to load static files (css, js, img) in a Web page, you need to specify a different directory to store static files, when the browser makes a request for non-HTML file, the server will go into this directory to find relevant documents.
Add a directory to store static files 1. Under the project directory is public.
2. Add the public directory under three storage js, css, img directory, the corresponding name is javascripts, stylesheets, images.
3. Then you can put the relevant files into the appropriate directory.
4. For example, the browser issues a request following style sheet:

<link href="/stylesheets/bootstrap.min.css" rel="stylesheet" media="screen">

The server side to the public / stylesheets / directory to find bootstrap.min.css file.
With a static catalog file, we have to tell it in a startup file this static file path, you need to specify it as follows:

app.use(express.static(require('path').join(__dirname, 'public')));

PS: express.static - specified search directory static files.
Use function calls using middleware designated express static access the directory, 'public' is what we used to store our new overall directory static files.

Add View

Well, here we have to add a page template, the project we will create a separate directory for storing template file, where we put on the root path of unity.
Let's start a new index.html, login.html, home.html three pages.
index.html page references are as follows:

login.html page references are as follows:

home.html page references are as follows:

And static files, we have to set the directory stored views, as follows:

// 设定views变量,意为视图存放的目录
app.set('views', __dirname);

With web templates and specify a directory, the following can access them.

Render View

How do we access it on the page template, which use to render the object function res.
1.render function, the web page template for rendering.
2. Format: res.render (view, [about locals], callback);
3. view parameter is the file name of the template callback for processing the returned string rendered, options, callback may be omitted, locals when rendering the template may be incoming variable values for the template, the template can be called preaching variables, and later we will tell the specific use, but also the first to see the effect on their own use.
4. For example, rendering index.html page we just added, we can write the following in app.js in:

var express = require('express');
var app = express();
var path = require('path');
 
app.set('views', __dirname);
 
app.set( 'view engine', 'html' );
app.engine( '.html', require( 'ejs' ).__express );
 
app.get('/', function(req, res) {
    res.render('index');
});
 
app.listen(80);

After running the test address, we can see the rendered index page, and whether to try other pages can also be rendered successful?

url redirection (redirect basic usage)

The method allows the redirect URL redirection, jump to a specific url and may specify the Status, 302 default mode.
Format: res.redirect ([status], url );
Example 1: Using a full url jump to a different domain name.

res.redirect("http://www.hubwiz.com");

Example 2: Jump specified page, such as the landing page, as follows:

res.redirect("login");

Later we began to realize the landing function, first try redirect redirect, how to jump to our website?

Realization landing

Access view

We've already added the view template and learned how to access the view, then we first look.
1. Refer to the following code, the address bar to access these paths to see if the request can be successful.

app.get('/', function(req, res) {
    res.render('index');
});
 
app.get('/login',function(req,res){
    res.render('login');
});
 
app.get('/home',function(req,res){
    res.render('home');
});

When the browser to see the corresponding view page it shows that our code is no problem, continue to fuel it!

Post request (user login)

Earlier we learned the express request of the get method, today we learn its post request method.
1.post Method - The path to process the request sent by the client Post request.
2. Format: app.post (path, function (REQ, res));
3. the same and get methods, path is the path request, the second parameter is a callback function processing request, and res represent REQ request information and response information.
4. For example post login request processing, the following examples

app.post('/login',function(req,res){
});

Understand the post method, here we start using post to achieve a simple user login functionality.

Post Request - body (1)

Before implementing the landing we start to understand a property - body.
Analytical properties of the body post client request parameters, which can be obtained by the parameter value of the path request.
Format: req.body parameter name;.
Here we test the function of body attributes, do some preparation.
Modify login.html, increase landing event for the Login button.
<input type="button" onclick="login();" value="登 陆">

function login(){
   var username = $('#username').val();
   var data = { "username": username };
   $.ajax({
           url:'/login',
           type:'POST',
           data:data
          });
}

To use the post body attribute parse request parameter values, we need to install and two intermediate reference body-parser multer express and specific methods are as follows:
2.1 Installation

npm install body-parser
npm install multer

2.2 references and call

var bodyParser = require('body-parser');
var multer = require('multer');
   ......
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());

And a body-parser multer middleware for processing data and post parse request.
Description: multer middleware versions of this course is using 0.1.6, its API has been different in the latest version (1.1.0) in. If you want to use in the project new version of multer, please refer to the official documentation , or specify the version at the time of installation:

npm install [email protected]

Post Request - body (2)

Here we can test post request body simple use of the property.
After the complete file 1. Modify good app.js as follows:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
app.set('views', __dirname);
app.set( 'view engine', 'html' );
app.engine( '.html', require( 'ejs' ).__express );
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());
app.get('/',function(req,res){
    res.render('login');
});
app.post("/login", function(req, res) {
    console.log("用户名称为:" + req.body.username);
});
app.listen(80);

Accessed through a browser test address, try entering any user name to log on, see if you can achieve success through body property?

Post landing 1

Then we began to realize the landing feature that allows us to do some preparatory work, add a click event, a link to the relevant button.

1. Modify index.html, increase landing link.
[登 录](login)
2. Strengthen the login page login method to achieve a simple post request:

 function login(){
    var username = $('#username').val();
    var password = $('#password').val();
    var data = { "username": username, "password":password};
    $.ajax({
             url:'login',
             type:'POST',
             data:data,
             success:function(data,status){
                  if(status == 'success'){
                      location.href='home';
                    }
             },
             error:function(data,status,e){
                  if(status == "error"){
                       location.href='login';
                     }
                   }
               });
       }

Web page templates ready ready, let's start modifying the contents of the startup files app.js.

Post landed 2

Here we begin to modify the contents of the app startup files.

1. Modify the post method, assuming the name of the database user name is admin, password is admin.

app.post('/login',function(req,res){
    var user={
        username:'admin',
        password:'admin'
    }
if(req.body.username==user.username&&req.body.password==user.password)
    { 
       res.send(200);
    }else{
       res.send( 404 );
    }
});

2. A complete startup file app.js as follows:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
 
app.set('views', __dirname);
app.set( 'view engine', 'html' );
app.engine( '.html', require( 'ejs' ).__express );
 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());
 
app.get('/', function(req, res) {
    res.render('index');
});
app.get('/home',function(req,res){
    res.render('home');
});
app.get('/login',function(req,res){
    res.render('login');
});
app.post('/login',function(req,res){
    var user={
        username:'admin',
        password:'admin'
    }
 if(req.body.username==user.username&&req.body.password==user.password)      {
      res.send(200);
   }else{
      res.send( 404 );
   }
});
 
app.listen(80);

Here, a simple Post login is complete, run the local port to try the effect of using browser!

Access Control page 1

Simple landing portion in accordance with our requirements have been completed, but the site is not better security, we found that repeated testing, home.html page was originally only accessible after landing, and now we do not need to log in, you can also be accessed directly in the browser input, this certainly can not be allowed, then we have to re-login function to be strengthened.
1.login.html increase EJS page template variable <% - message%> Save login prompt.

...
    <%- message %>
# 用户登录
...

2.home.html page, after a successful jump and landing incoming Username:

# 恭喜_<%= user.username %>_,登陆成功!

PS: Use EJS template variable values using <% = variable_name%> output, the default escape through escape character string encoded output. When we want to export some dynamically generated HTML tags can be used <% - variable_nam%> output, this approach can not be escaped escape coded.
3.home.html page add an exit link, as follows:

[退 出](logout)

Page 2 Access Control

Well modify template pages, you can start to modify the contents of the startup files app.js.
1. Install Module express-session and references, installation, not about the reference.
2. Use the new module to access time restrictions, as follows:

var session = require('express-session');
...
app.use(session({
    secret:'secret',
    resave:true,
    saveUninitialized:false,
    cookie:{
        maxAge:1000*60*10  //过期时间设置(单位毫秒)
    }
}));

3.app.js middleware new file and set the template variable values, as follows:

app.use(function(req, res, next){
    res.locals.user = req.session.user;
    var err = req.session.error;
    res.locals.message = '';
    if (err) res.locals.message = '<div style="margin-bottom: 20px;color:red;">' + err + '</div>';
    next();
});

Local variable value in response to body res.locals objects stored in the first request in the range.
PS: Note that the order of placement of the middleware is very important, is equivalent to the execution order. Moreover, the middleware must be placed before the verb HTTP method will not execute.

4. Increase path logout processing (login user exit) index and a route request processing, as follows:

app.get('/logout', function(req, res){
    req.session.user = null;
    req.session.error = null;
    res.redirect('index');
});
app.get('/index', function(req, res) {
    res.render('index');
});

5. Modify the home path request processing, as follows:

app.get('/home',function(req,res){
    if(req.session.user){
        res.render('home');
    }else{
        req.session.error = "请先登录"
        res.redirect('login');
    }
});

5. Post modify the path of a request for login

app.post('/login',function(req,res){
    var user={
        username:'admin',
        password:'admin'
    }
 if(req.body.username==user.username&&req.body.password==user.password){
        req.session.user = user;
        res.send(200);
    }else{
        req.session.error = "用户名或密码不正确";
        res.send( 404 );
    }
});

Well, the entire modification is completed, access to the test address again try the effect of it!

Routing landing

Use Route 1

---- routes for different access path, specify a different approach. In app.js we specify app.get, multiple routing rules different paths app.post in the actual development of applications, will run into the situation of having multiple routing records for this problem, we have to these routing records do separately, to facilitate management.
We make the following modifications on the basis of landed example.
1. Add three js file names are login, home, logout.
2.login.js file, add the following:

module.exports = function ( app ) {
    app.get('/login',function(req,res){
        res.render('login');
    });
 
    app.post('/login',function(req,res){
        var user={
            username:'admin',
            password:'admin'
        }
        if(req.body.username==user.username&&req.body.password==user.password){
            req.session.user = user;
            res.send(200);
        }else{
            req.session.error = "用户名或密码不正确"
            res.send( 404 );
        }
    });
}

3.home.js file, add the following:

module.exports = function ( app ) {
    app.get('/home',function(req,res){
        if(req.session.user){
            res.render('home');
        }else{
            req.session.error = "请先登录"
            res.redirect('login');
        }
    });
}

Use Route 2

4.logout.js file, add the following:

module.exports = function ( app ) {
    app.get('/logout', function(req, res){
        req.session.user = null;
        req.session.error = null;
        res.redirect('index');
    });
}

5.app.js file request path logout, home, login code can be deleted
6. The three new file to change how we use it, is very simple, as follows:

require('./login')(app);
require('./home')(app);
require('./logout')(app);

Yes, that's so simple, we simply reference the directory to route.
Here our user login feature is safe, off now quickly try the effect of it!

Published 42 original articles · won praise 4 · Views 4621

Guess you like

Origin blog.csdn.net/lucasxt/article/details/90177214