【问题标题】:Routing errors with expressjs and object constructorsexpressjs 和对象构造函数的路由错误
【发布时间】:2015-12-09 20:51:26
【问题描述】:

我正在使用 express 和 nodejs 创建一个 API REST,并且我处于路由的早期阶段。

我的想法是为每个分离的路由创建“控制器”,并在路由器文件中调用该控制器,例如:

...
router.post('/login', loginCtrl.login(req, res));

在其他项目中,我使用一个简单的函数对象来处理它,需要它,然后调用该函数。现在我的想法更有趣了,我正在使用对象构造函数,例如:

var ctrl = function() {
   this.login = function(req, res) {
     res.json({ msg: 'hello' }); // just an example
   }
}

我在coffeescript上写这个(客户想要咖啡,所以......)并且sintax与那个元语言但至少是相同的,我的问题是reqres,这是我的路由器文件:

express = require 'express'
router = express.Router()

###
  Rutas de autenticación
###
AuthController = require '../controllers/authenticate'
auth = new AuthController()

router.post '/setup'   , auth.setup req, res
router.post '/register', auth.register req, res
router.post '/login'   , auth.login req, res

module.exports = router

当服务器运行时,它会抛出这个错误:

/home/nano/Dev/erp-api/app/routes/apiroutes.coffee:17
  router.post('/setup', auth.setup(req, res));
                                   ^
ReferenceError: req is not defined

究竟为什么会发生这种情况?我不知道,当我使用普通对象时它可以工作。

【问题讨论】:

    标签: javascript node.js rest express coffeescript


    【解决方案1】:

    就像你一样,你正在使用变量调用函数设置,而你想要的是传递对函数的引用。所以你只需要传递对它的引用而不是执行它。

    router.post '/setup'   , auth.setup
    

    req, res 会自动传递给那个函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 2018-01-18
      相关资源
      最近更新 更多