[关闭]
@JunQiu 2018-09-18T17:48:31.000000Z 字数 3342 阅读 1272

express(route、中间件)、log(morgan))

summary_2018/06 express


1、日常工作


2、技术学习

  1. ### Example
  2. var express = require('express')
  3. var app = express()
  4. // respond with "hello world" when a GET request is made to the homepage
  5. app.get('/', function (req, res) {
  6. res.send('hello world')
  7. })
  8. ### Route paths(支持正则表达式)
  9. //路径将匹配/abe并/abcde。
  10. app.get('/ab(cd)?e', function (req, res) {
  11. res.send('ab(cd)?e')
  12. })
  13. ### app.route(),便于模块化
  14. app.route('/book')
  15. .get(function (req, res) {
  16. res.send('Get a random book')
  17. })
  18. .post(function (req, res) {
  19. res.send('Add a book')
  20. })
  21. .put(function (req, res) {
  22. res.send('Update the book')
  23. })
  24. ### express.Router(一个Router实例是一个完整的中间件和路由系统; 出于这个原因,它通常被称为“迷你应用程序”。)
  25. //birds.js
  26. var express = require('express')
  27. var router = express.Router()
  28. // middleware that is specific to this router
  29. router.use(function timeLog (req, res, next) {
  30. console.log('Time: ', Date.now())
  31. next()
  32. })
  33. // define the about route
  34. router.get('/about', function (req, res) {
  35. res.send('About birds')
  36. })
  37. module.exports = router
  38. //在应用程序中加载路由器模块
  39. var birds = require('./birds')
  40. //http://127.0.0.1:4000/birds/about
  41. app.use('/birds', birds)
  42. ### 路由参数
  43. Route path: /users/:userId/books/:bookId
  44. Request URL: http://localhost:3000/users/34/books/8989
  45. req.params: { "userId": "34", "bookId": "8989" }
  46. //querystring,支持async
  47. app.get('/ins', async (req, res) => {
  48. console.log(req.query)
  49. }
  50. ### responseMethod
  51. Method Description
  52. res.download() Prompt a file to be downloaded.
  53. res.end() End the response process.
  54. res.json() Send a JSON response.
  55. res.jsonp() Send a JSON response with JSONP support.
  56. res.redirect() Redirect a request.
  57. res.render() Render a view template.
  58. res.send() Send a response of various types.
  59. res.sendFile() Send a file as an octet stream.
  60. res.sendStatus() Set the response status code and send its string representation as the response body.
  1. var express = require('express')
  2. var app = express()
  3. //定义中间件
  4. var requestTime = function (req, res, next) {
  5. req.requestTime = Date.now()
  6. next()
  7. }
  8. //使用中间件
  9. app.use(requestTime)
  10. app.get('/', function (req, res) {
  11. var responseText = 'Hello World!<br>'
  12. responseText += '<small>Requested at: ' + req.requestTime + '</small>'
  13. res.send(responseText)
  14. })
  15. app.listen(3000)
  16. ### 可配置的中间件(传递参数)
  17. 文件: my-middleware.js
  18. module.exports = function(options) {
  19. return function(req, res, next) {
  20. // 根据参数配置
  21. next()
  22. }
  23. }
  24. 使用中间件,如下所示。
  25. var mw = require('./my-middleware.js')
  26. app.use(mw({ option1: '1', option2: '2' }))
  27. ### 中间件堆栈
  28. app.use('/user/:id', function (req, res, next) {
  29. console.log('Request URL:', req.originalUrl)
  30. next()
  31. }, function (req, res, next) {
  32. console.log('Request Type:', req.method)
  33. next()
  34. })
  35. #### 应用程序级
  36. var app = express()
  37. //没有路由功能,任何应用程序收到都会执行
  38. app.use(function (req, res, next) {
  39. console.log('Time:', Date.now())
  40. next()
  41. })
  42. // /user/:id路径上安装的中间件功能
  43. app.use('/user/:id', function (req, res, next) {
  44. console.log('Request Type:', req.method)
  45. next()
  46. })
  47. //路由器中间件堆栈
  48. app.get('/user/:id', function (req, res, next) {
  49. // if the user ID is 0, skip to the next route
  50. if (req.params.id === '0') next('route')
  51. // otherwise pass the control to the next middleware function in this stack
  52. else next()
  53. }, function (req, res, next) {
  54. // render a regular page
  55. res.render('regular')
  56. })
  57. Tips:跳过路由器中间件堆栈中的其余中间件功能,调用next('route')以将控制权传递给下一个路由。仅适用于使用app.METHOD()或router.METHOD()功能加载的中间件功能。
  58. // handler for the /user/:id path, which renders a special page
  59. app.get('/user/:id', function (req, res, next) {
  60. res.render('special')
  61. })
  62. #### 路由级中间件
  63. //由器级中间件的工作方式与应用级中间件的工作方式相同,只是它绑定到一个实例express.Router()。
  64. #### 错误处理中间件
  65. app.use(function (err, req, res, next) {
  66. console.error(err.stack)
  67. res.status(500).send('Something broke!')
  68. })
  69. #### 内置中间件和第三方中间件
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注