1.  什么是router路径,什么是middleware?

我们输入www.baidu.com 来访问百度的主页,浏览器会自动转换为 http://www.baidu.com:80/(省略一些参数)。 http://代表我们同服务器连接使用的是http协议,www.baidu.com 代表的是服务器的主机地址,会被我们的pc通过DNS解析为IP地址。80是默认的应用层端口。/ 即为我们访问的服务器(www.baidu.com)的路径,服务器要对我们访问的这个路径做出响应,采取一定的动作。我们可以把这一过程看做一个路由。

访问的路径‘/’即为router的路径,服务器采取的动作即为middleware,即为一个个特殊的函数。

  2. router路径

  www.baidu.com/test: 路径为 /test

www.baidu.com/test?name=1&number=2: 路径同样为/test, ?后面会被服务器理解传给路径的参数。

   3. Middleware 

An Express application is essentially a stack of middleware which are executed serially.(express应用其实就是由一系列顺序执行的Middleware组成。)
A middleware is a function with access to the request object (req), the response object (res), and the next middleware in line in the request-response cycle of an Express application. It is commonly denoted by a variable named next. Each middleware has the capacity to execute any code, make changes to the request and the reponse object, end the request-response cycle, and call the next middleware in the stack. Since middleware are execute serially, their order of inclusion is important.(中间件其实就是一个访问express应用串入的req,res,nex参数的函数,这个函数可以访问任何通过req,res传入的资源。)
If the current middleware is not ending the request-response cycle, it is important to call next() to pass on the control to the next middleware, else the request will be left hanging.(如果当前中间件没有完成对网页的res响应 ,还可以通过next把router 留给下一个middleware继续执行)
With an optional mount path, middleware can be loaded at the application level or at the router level. Also, a series of middleware functions can be loaded together, creating a sub-stack of middleware system at a mount point.

  路由的产生是通过HTTP的各种方法(GET, POST)产生的,Middleware可以跟router路径跟特定的HTTP方法绑定,也可以跟所有的方法绑定。

  3.1 通过express应用的use(all),把Middleware同router路径上的所有HTTP方法绑定:

 app.use(function (req, res, next) {
console.log('Time: %d', Date.now());
next();
})

  3.2 通过express应用的http.verb,把Middleware同router路径上的特定的HTTP方法绑定:

 app.get('/', function(req, res){
res.send('hello world');
}); app.post('/', function(req, res){
res.send('hello world');
});

  4.  Express的Router对象

  当express实例的路由越来越多的时候,最好把路由分类独立出去,express的实例(app) 能更好的处理其他逻辑流程。Express的Router对象是一个简化的 app实例,只具有路由相关的功能,包括use, http verbs等等。最后这个Router再通过app的use挂载到app的相关路径下。

 var express = require('express');
var app = express();
var router = express.Router(); // simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use(function(req, res, next) {
console.log('%s %s %s', req.method, req.url, req.path);
next();
}); // this will only be invoked if the path ends in /bar
router.use('/bar', function(req, res, next) {
// ... maybe some additional /bar logging ...
next();
}); // always invoked
router.use(function(req, res, next) {
res.send('Hello World');
}); app.use('/foo', router); app.listen(3000);

  router的路由必须通过app.use和app.verbs 挂载到app上才能被响应。所以上述代码,只有在app捕捉到 /foo路径上的路由时,才能router中定义的路由,虽然router中有针对 '/' 的路由,但是被app中的路由给覆盖了。

附:app.verbs和app.use的路由路径区别:

先看一段测试代码:

 var express = require('express');

 var app = express();
var router = express.Router(); app.get('/', function(req, res){
console.log('test1');
}); app.use('/', function(req, res){
console.log('test2');
}); router.get('/', function(req, res){
console.log('test3');
}); app.listen(4000);

输入url: localhost:4000

输出结果:test1
 
输入url: localhost:4000/hello
输出结果:test2
 
  结论:app.get挂载‘/’的路由只响应跟'/'精确匹配的GET请求。 而app.use挂载的'/'的路由响应所有以'/' 为起始路由的路由,且不限制HTTP访问的方法。以下说明:Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path.
 
 app.use([path], [function...], function)
Mount the middleware function(s) at the path. If path is not specified, it defaults to "/". Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path.

express 框架之 路由与中间件的更多相关文章

  1. http协议、模块、express框架以及路由器、中间件和mysql模块

    一.http协议 是浏览器和web服务器之间的通信协议 1.通用头信息 request url:请求的url,向服务器请求的数据 request method:请求的方式   get.post sta ...

  2. express 洋葱模型 路由管理 中间件

    express 路由管理,通过 app.express();  app.METHOD(path,fn(req, res)的方式进行路由的配置.实现了请求的接口的路由的拆分.那么可以将路由配置,分发到不 ...

  3. nodejs开发 express路由与中间件

    路由 通常HTTP URL的格式是这样的: http://host[:port][path] http表示协议. host表示主机. port为端口,可选字段,不提供时默认为80. path指定请求资 ...

  4. nodejs学习笔记二:解析express框架项目文件

    上一章介绍了如何去创建一个express框架的工程项目,这章介绍一下express框架下的文件和用法解析,上一张我们创建的工程项目结构图如下: models是不属于原工程项目结构,为了实现数据模型后添 ...

  5. nodejs的express框架

    介绍: Express是由路由和中间件构成一个的nodejs的一种web应用框架; 功能: 可以设置中间件来响应 HTTP 请求. 定义了路由表用于执行不同的 HTTP 请求动作. 可以通过向模板传递 ...

  6. node.js之express框架入门篇

    一.express框架简介 express框架是后台的Node框架,在后台的受欢迎的程度,和jQuery一样 英语官网:http://expressjs.com/ 中文官网:http://www.ex ...

  7. express框架之1

    express框架: 1.依赖中间件 2.接受请求 get / post / use get('/地址' , function(req , resp ){}) post和use 同理 3.非破坏式 4 ...

  8. express框架安装及中间件原理

    本文主要介绍express中间件的原理,来应对面试. 1.安装express及初始化: npm install express-generator -g   =>   express expre ...

  9. node/静态路由/express框架中的express.static()和app.use()

    此篇文章转载于 express框架中的express.static()和app.use() Express框架在使用app.use中传入express.static设置静态路由时,这个文件夹下的所有文 ...

随机推荐

  1. TCP/IP详解 笔记十三

    TCP协议(一) 概述 特点 1,  面向连接可靠的字节流服务 2,  只有两方通信,不能用于广播或多播 3,  应用数据被TCP分隔为最合适发送的数据段,传给IP协议栈 4,  发送端并启动定时器, ...

  2. 如何在Visual Studio 2013中使用Ribbon For WPF

    1.首先需要 下载Ribbon For WPF.目前最新的版本是Microsoft Ribbon for WPF October 2010. 下载 链接: https://www.microsoft. ...

  3. jQuery知识点总结(第四天)

    前三天是jQuery的基础部分,选择器学好了.才能进行下一步的操作,如果前三天没学过没学好,不要跳着学.粗俗的话叫做,步子大了,容易扯着蛋.一步一个脚印,是最好的方式. 强调一下.有问题,不要憋着不讲 ...

  4. hibernate----(Hql)查询

    package com.etc.test; import java.util.List;import java.util.Properties; import org.hibernate.Query; ...

  5. confluence安装

    confluence安装 1.jre安装 java下载http://www.java.com/zh_CN/download/manual.jsp 创建目录和解压缩 mkdir -p /usr/loca ...

  6. 转: CvMat,Mat和IplImage之间的转化和拷贝

    1.CvMat之间的复制 //注意:深拷贝 - 单独分配空间,两者相互独立 CvMat* a; CvMat* b = cvCloneMat(a); //copy a to b 2.Mat之间的复制 / ...

  7. IBatis学习

    (1)建立 SqlMap.config文件 <?xml version="1.0" encoding="utf-8" ?> <sqlMapCo ...

  8. Win8.1微软官方最终正式版ISO镜像文件

    Win8.1微软官方最终正式版ISO镜像文件 经过预览版,测试版.开发版本等几个乱七八糟的版本后,2013年10月17日,微软终于如约的发布了Win8.1最终正式版. Win8.1和win8的区别 1 ...

  9. mysql循环获取结果集

    do { MYSQL_RES* res = mysql_store_result(con); ) { MYSQL_ROW row; if (row = mysql_fetch_row(res)) { ...

  10. ArcGIS Server 10.1 for Linux典型问题总结

    关闭开启server服务: [gis@localhost ArcGISServer]$ cd /home/gis/arcgis/server [gis@localhost server]$ ./sto ...