代码之家  ›  专栏  ›  技术社区  ›  user180574

为什么express.Router()不工作?

  •  1
  • user180574  · 技术社区  · 7 年前

    我尝试测试示例代码bird.js( https://expressjs.com/en/guide/routing.html ). 基本上,像下面这样。

    var express = require('express')
    var router = express.Router()
    
    router.use(function timeLog (req, res, next) {
      console.log('Time: ', Date.now())
      next()
    })
    

    但当我运行它时。

    node bird.js
    

    我知道这个错误。

    TypeError: Cannot read property 'use' of undefined
    

    顺便说一下,安装了“Express”。

    额外信息 “express”:“3.2.x”,

    TypeError: Cannot read property 'use' of undefined
        at Object.<anonymous> (../route/bird.js:5:7)
        at Module._compile (module.js:410:26)
        at Object.Module._extensions..js (module.js:417:10)
        at Module.load (module.js:344:32)
        at Function.Module._load (module.js:301:12)
        at Function.Module.runMain (module.js:442:10)
        at startup (node.js:136:18)
        at node.js:966:3
    

    我跑的全是bird.js。

    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
    
    3 回复  |  直到 7 年前
        1
  •  1
  •   Marcos Casagrande    7 年前

    问题是您使用的是过时的快速版本你所指的文件是 4.x.x ,而您正在使用 3.x.x .

    将您的Express版本更新为最新版本,您的代码将正常工作。

    npm install express@latest
    

    将快速版本更新为: 4.16.3

        2
  •  0
  •   vitomadio    7 年前

    你应该这样试试。

    router.use('/',timeLog, function(req, res, next) {
        console.log('Time: ', Date.now())
        next()
    })
    

    希望能有所帮助。

        3
  •  0
  •   Cesar N Mejia Leiva    7 年前

    您需要通过调用 const app = express() . 然后将bird.js导入app.js并运行 node app.js 是的。

    见下图: enter image description here

    推荐文章