express 整理

「爱情、让人受尽委屈。」 2022-06-04 01:20 103阅读 0赞

基本路由:

  1. var express = require('express');
  2. var router = express.Router();
  3. var test= require('../dao/sqlTest');
  4. router.post('/getAllAccount', function(req, res){
  5. sqlTest.getAllAccount(req, res);
  6. });
  7. var testRoutes = require('../routes/上面的文件'),
  8. app.use('/test',testRoutes);

静态托管:

  1. app.use(express.static('public'));
  2. 现在,public 目录下面的文件就可以访问了。
  3. http://localhost:3000/images/kitten.jpg
  4. http://localhost:3000/css/style.css
  5. http://localhost:3000/js/app.js
  6. http://localhost:3000/images/bg.png
  7. http://localhost:3000/hello.html

重点是中间件的应用:

  1. 应用级中间件
  2. 应用级中间件绑定到 app 对象 使用 app.use() app.METHOD(), 其中, METHOD 是需要处理的 HTTP 请求的方法,例如 GET, PUT, POST 等等,全部小写。例如:
  3. var app = express();
  4. // 没有挂载路径的中间件,应用的每个请求都会执行该中间件
  5. app.use(function (req, res, next) {
  6. console.log('Time:', Date.now());
  7. next();
  8. });
  9. // 挂载至 /user/:id 的中间件,任何指向 /user/:id 的请求都会执行它
  10. app.use('/user/:id', function (req, res, next) {
  11. console.log('Request Type:', req.method);
  12. next();
  13. });
  14. // 路由和句柄函数(中间件系统),处理指向 /user/:id 的 GET 请求
  15. app.get('/user/:id', function (req, res, next) {
  16. res.send('USER');
  17. });
  18. 下面这个例子展示了在一个挂载点装载一组中间件。
  19. // 一个中间件栈,对任何指向 /user/:id 的 HTTP 请求打印出相关信息
  20. app.use('/user/:id', function(req, res, next) {
  21. console.log('Request URL:', req.originalUrl);
  22. next();
  23. }, function (req, res, next) {
  24. console.log('Request Type:', req.method);
  25. next();
  26. });
  27. 作为中间件系统的路由句柄,使得为路径定义多个路由成为可能。在下面的例子中,为指向 /user/:id GET 请求定义了两个路由。第二个路由虽然不会带来任何问题,但却永远不会被调用,因为第一个路由已经终止了请求-响应循环。
  28. // 一个中间件栈,处理指向 /user/:id 的 GET 请求
  29. app.get('/user/:id', function (req, res, next) {
  30. console.log('ID:', req.params.id);
  31. next();
  32. }, function (req, res, next) {
  33. res.send('User Info');
  34. });
  35. // 处理 /user/:id, 打印出用户 id
  36. app.get('/user/:id', function (req, res, next) {
  37. res.end(req.params.id);
  38. });
  39. 如果需要在中间件栈中跳过剩余中间件,调用 next('route') 方法将控制权交给下一个路由。 注意: next('route') 只对使用 app.VERB() router.VERB() 加载的中间件有效。
  40. // 一个中间件栈,处理指向 /user/:id 的 GET 请求
  41. app.get('/user/:id', function (req, res, next) {
  42. // 如果 user id 为 0, 跳到下一个路由
  43. if (req.params.id == 0) next('route');
  44. // 否则将控制权交给栈中下一个中间件
  45. else next(); //
  46. }, function (req, res, next) {
  47. // 渲染常规页面
  48. res.render('regular');
  49. });
  50. // 处理 /user/:id, 渲染一个特殊页面
  51. app.get('/user/:id', function (req, res, next) {
  52. res.render('special');
  53. });
  54. 路由级中间件
  55. 路由级中间件和应用级中间件一样,只是它绑定的对象为 express.Router()。
  56. var router = express.Router();
  57. 路由级使用 router.use() router.VERB() 加载。
  58. 上述在应用级创建的中间件系统,可通过如下代码改写为路由级:
  59. var app = express();
  60. var router = express.Router();
  61. // 没有挂载路径的中间件,通过该路由的每个请求都会执行该中间件
  62. router.use(function (req, res, next) {
  63. console.log('Time:', Date.now());
  64. next();
  65. });
  66. // 一个中间件栈,显示任何指向 /user/:id 的 HTTP 请求的信息
  67. router.use('/user/:id', function(req, res, next) {
  68. console.log('Request URL:', req.originalUrl);
  69. next();
  70. }, function (req, res, next) {
  71. console.log('Request Type:', req.method);
  72. next();
  73. });
  74. // 一个中间件栈,处理指向 /user/:id 的 GET 请求
  75. router.get('/user/:id', function (req, res, next) {
  76. // 如果 user id 为 0, 跳到下一个路由
  77. if (req.params.id == 0) next('route');
  78. // 负责将控制权交给栈中下一个中间件
  79. else next(); //
  80. }, function (req, res, next) {
  81. // 渲染常规页面
  82. res.render('regular');
  83. });
  84. // 处理 /user/:id, 渲染一个特殊页面
  85. router.get('/user/:id', function (req, res, next) {
  86. console.log(req.params.id);
  87. res.render('special');
  88. });
  89. // 将路由挂载至应用
  90. app.use('/', router);
  91. 错误处理中间件
  92. 错误处理中间件有 4 个参数,定义错误处理中间件时必须使用这 4 个参数。即使不需要 next 对象,也必须在签名中声明它,否则中间件会被识别为一个常规中间件,不能处理错误。
  93. 错误处理中间件和其他中间件定义类似,只是要使用 4 个参数,而不是 3 个,其签名如下: (err, req, res, next)。
  94. app.use(function(err, req, res, next) {
  95. console.error(err.stack);
  96. res.status(500).send('Something broke!');
  97. });
  98. 请参考 错误处理 一章了解更多关于错误处理中间件的内容。
  99. 内置中间件
  100. 4.x 版本开始,, Express 已经不再依赖 Connect 了。除了 express.static, Express 以前内置的中间件现在已经全部单独作为模块安装使用了。请参考 中间件列表。
  101. express.static(root, [options])
  102. express.static Express 唯一内置的中间件。它基于 serve-static,负责在 Express 应用中提托管静态资源。
  103. 参数 root 指提供静态资源的根目录。
  104. 可选的 options 参数拥有如下属性。
  105. 属性 描述 类型 缺省值
  106. dotfiles 是否对外输出文件名以点(.)开头的文件。可选值为 allow”、“deny ignore String ignore
  107. etag 是否启用 etag 生成 Boolean true
  108. extensions 设置文件扩展名备份选项 Array []
  109. index 发送目录索引文件,设置为 false 禁用目录索引。 Mixed index.html
  110. lastModified 设置 Last-Modified 头为文件在操作系统上的最后修改日期。可能值为 true false Boolean true
  111. maxAge 以毫秒或者其字符串格式设置 Cache-Control 头的 max-age 属性。 Number 0
  112. redirect 当路径为目录时,重定向至 “/”。 Boolean true
  113. setHeaders 设置 HTTP 头以提供文件的函数。 Function
  114. 下面的例子使用了 express.static 中间件,其中的 options 对象经过了精心的设计。
  115. var options = {
  116. dotfiles: 'ignore',
  117. etag: false,
  118. extensions: ['htm', 'html'],
  119. index: false,
  120. maxAge: '1d',
  121. redirect: false,
  122. setHeaders: function (res, path, stat) {
  123. res.set('x-timestamp', Date.now());
  124. }
  125. }
  126. app.use(express.static('public', options));
  127. 每个应用可有多个静态目录。
  128. app.use(express.static('public'));
  129. app.use(express.static('uploads'));
  130. app.use(express.static('files'));
  131. 更多关于 serve-static 和其参数的信息,请参考 serve-static 文档。
  132. 第三方中间件
  133. 通过使用第三方中间件从而为 Express 应用增加更多功能。
  134. 安装所需功能的 node 模块,并在应用中加载,可以在应用级加载,也可以在路由级加载。
  135. 下面的例子安装并加载了一个解析 cookie 的中间件: cookie-parser
  136. $ npm install cookie-parser
  137. var express = require('express');
  138. var app = express();
  139. var cookieParser = require('cookie-parser');
  140. // 加载用于解析 cookie 的中间件
  141. app.use(cookieParser());

发表评论

表情:
评论列表 (有 0 条评论,103人围观)

还没有评论,来说两句吧...

相关阅读

    相关 express

    概述 Express 是基于 node.js 平台的一个简洁而灵活的应用程序开发框架;express 为 Web 和移动应用程序提供了一系列强大功能和丰富的 HTTP 实

    相关 Express基础

    1 简介 Express是一个基于Node平台的web应用开发框架,它提供了一系列的强大特性用来创建各种Web应用。 提供了方便简洁的路由定义方式; 对获取