【问题标题】:Express middleware that adds more middleware and routesExpress 中间件,增加了更多的中间件和路由
【发布时间】:2020-10-21 02:50:06
【问题描述】:

我有一个如下所示的 Node/Express 应用程序:

app.use(foo)
...
app.get('/foo/bar', ...)
...
app.get('/index', ...)

我想提取中间件和路由,以便现在可以这样做:

app.use(myMiddlewareAndRoutes)
...
app.get('/index', ...)

这样myMiddlewareAndRoutes添加了中间件foo和属于它的路由'/foo/bar'

我该怎么做?

【问题讨论】:

  • 中间件增加更多路由没有意义。对大量传入请求重复调用中间件。您不希望它一遍又一遍地添加路线。我的建议是你备份几个步骤并描述你的实际问题,而不是仅仅描述你对一个你没有完全描述的问题的尝试解决方案。
  • 这能回答你的问题吗? How to separate routes on Node.js and Express 4?
  • 也许你想使用一个单独的路由器,上面有/foo/foo/bar路由,然后你可以在一个语句中app.use(router)

标签: javascript node.js express middleware


【解决方案1】:
var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds')
})

module.exports = router
var birds = require('./birds')

// ...

app.use('/birds', birds)
//or if you need it on root level
app.use('/', birds)

【讨论】:

    【解决方案2】:

    您想创建一个单独的 Router 对象,然后使用 .use() 函数将其添加为中间件。

    foo.js 文件中,我正在创建一个新路由器并将其导出:

    foo.js

    const { Router } = require('express');
    const router = Router();
    
    router.get('/bar', (req, res, next) => {
        return res.send('bar');
    });
    
    module.exports = router;
    

    然后将其导入index.js文件中以将其添加为中间件:

    index.js

    const express = require('express');
    const foo = require('./foo.js');
    
    const app = express();
    
    app.use('/foo', foo);
    
    app.get('/index', ...)
    

    现在您在foo.js 中定义的每条路由都将使用/foo 前缀,例如/foo/bar

    【讨论】:

      猜你喜欢
      • 2019-06-09
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 2023-03-25
      • 1970-01-01
      • 2017-03-08
      • 2015-11-16
      相关资源
      最近更新 更多