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方法绑定:

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

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

1 app.get('/', function(req, res){
2   res.send('hello world');
3 });
4
5
6 app.post('/', function(req, res){
7   res.send('hello world');
8 });

  4.  Express的Router对象

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

 1 var express = require('express');
 2 var app = express();
 3 var router = express.Router();
 4
 5 // simple logger for this router's requests
 6 // all requests to this router will first hit this middleware
 7 router.use(function(req, res, next) {
 8   console.log('%s %s %s', req.method, req.url, req.path);
 9   next();
10 });
11
12 // this will only be invoked if the path ends in /bar
13 router.use('/bar', function(req, res, next) {
14   // ... maybe some additional /bar logging ...
15   next();
16 });
17
18 // always invoked
19 router.use(function(req, res, next) {
20   res.send('Hello World');
21 });
22
23 app.use('/foo', router);
24
25 app.listen(3000);

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

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

先看一段测试代码:

 1 var express = require('express');
 2
 3 var app = express();
 4 var router = express.Router();
 5
 6 app.get('/', function(req, res){
 7      console.log('test1');
 8 });
 9
10 app.use('/', function(req, res){
11      console.log('test2');
12 });
13
14 router.get('/', function(req, res){
15      console.log('test3');
16 });
17
18 app.listen(4000);

View Code

输入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.
1 app.use([path], [function...], function)
2 Mount the middleware function(s) at the path. If path is not specified, it defaults to "/".
3
4 Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path.

转载于:https://www.cnblogs.com/chenchenluo/p/4192282.html

express 框架之 路由与中间件相关推荐

  1. 渲染静态页面、get请求、post请求、express框架、路由、中间件

    1. 渲染静态页面 const http = require('http'); const fs = require('fs'); const url = require('url'); const ...

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

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

  3. Express 框架

    一.使用 express 命令 来快速从创建一个项目目录 1.全局安装Express及express-generator 命令: $ npm install  -g express $ npm ins ...

  4. express 路由中间件_Express通过示例进行解释-安装,路由,中间件等

    express 路由中间件 表达 (Express) When it comes to build web applications using Node.js, creating a server ...

  5. 对比原生Node封装的Express路由 和 express框架路由

    文章目录 前言 一.routes.js 1.引入模块 2.changesRes() - send() 3.getFileMime() - type() 4.initStatic 5.server() ...

  6. class07:Express框架、中间件

    这里写目录标题 一.express模块 1. 安装使用express 2. 设置跨域 二.中间件 1. 跨域中间件 2. 后端获取前端发送的数据 2.1 get方式 2.2 post方式 一.expr ...

  7. node.js express php,nodejs开发——express路由与中间件

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

  8. Express框架(http服务器 + 路由)

    index.js 使用express框架搭建http服务器,和实现路由功能. var express = require('express'); var app = express();// 主页输出 ...

  9. nodejs开发 过程中express路由与中间件的理解 - pyj063 - 博客园

    nodejs开发 过程中express路由与中间件的理解 nodejs开发 express路由与中间件 路由 通常HTTP URL的格式是这样的: http://host[:port][path] h ...

最新文章

  1. Android之getSystemService
  2. 软件工程--软件计划
  3. SpringBoot集成其他技术-集成Redis
  4. 问题:jquery给标签添加事件,但标签还未加载会成功吗
  5. teststand调用python模块_TestStand 基本知识[10]--在序列中调用代码模块之--LabVIEW
  6. 如何调整反光镜和座椅的位置 为您支招
  7. git 查看pop内容_原创 | 有了Git这个操作,我再也不怕代码混乱了!
  8. java的三种流程控制语录_Java 流程控制语句
  9. 解决 VS2008安装过程更改路径的问题
  10. PHP接收云之家审批结果,首页云之家开放平台文档
  11. 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
  12. 51CTO学院三周年-我的rhce7认证之路
  13. c语言程序运行超时是怎么回事,这个运行超时是什么原因?求助~
  14. 计算机考试用远程桌面,远程桌面客户端对服务器身份的验证
  15. nvidia jetson agx Xavier can 开机自动运行脚本
  16. 狸窝音频剪辑软件_5分钟学会影视剪辑:账号注册、素材寻找、剪辑使用、获取收益...
  17. 2×3卡方检验prism_抽样分布之卡方分布02 – 分布拟合优度检验
  18. 外企就很舒服?聊聊我在外企的工作体验
  19. python音乐下载器交互界面设计_用python实现的百度音乐下载器-python-pyqt-改进版...
  20. android 群英传笔记,Android 群英传读书笔记1

热门文章

  1. BZOJ2648 SJY摆棋子(KD-Tree)
  2. 洛谷P3245 [HNOI2016]大数 【莫队】
  3. 信号 应用场景 内置信号 内置信号操作 自定义信号
  4. js 实现图片旋转角度
  5. 在javascript当中发现了一个没有调用者的方法。
  6. C# 捕获系统闪退BUG
  7. C#实现软键盘的几个关键技术实现方法
  8. uni-app 发送form-data参数的请求方式传值给后台
  9. android usb多个,android、windows上多个USB Camera同时使用实验小结
  10. dbinfo.properties mysql_java 8.0Mysql 助手类