H
H
heducose2017-07-22 01:54:58
Node.js
heducose, 2017-07-22 01:54:58

Why does the code stop working after being moved to a separate controller?

I don’t understand why this code stops working if I try to refactor it and put it in a separate controller file?
Works:

router.get('/demo',
  jwt(
    { secret: process.env.SECRET }),
  function (req, res) {
    User.findById(req.user.sub, function (err, user) {
      if (err) { console.log('ERROR') }
      if (user) {
        res.send({
          eee: req.user,
          hi: 'SECRET test authorization of registered user'
        })
      } else {
        res.send('ERROR')
      }
    })
})

Does not work:
router.post('/demo', Authentication.secret)
exports.secret = function (req, res) {
  jwt(
    { secret: process.env.SECRET }),
  function (req, res) {
    User.findById(req.user.sub, function (err, user) {
      if (err) { console.log('ERROR') }
      if (user) {
        res.send({
          eee: req.user,
          hi: 'SECRET test authorization of registered user'
        })
      } else {
        res.send('ERROR')
      }
    })
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2017-07-22
@heducose

firstly, because jwt obviously returns middleware
; secondly, no one calls the internal function
correctly like this:

router.post('/demo', jwt({ secret: process.env.SECRET }),Authentication.secret)
exports.secret = function (req, res) {
    User.findById(req.user.sub, function (err, user) {
      // добавлю еще маленько хорошей практики обработки ошибок:
      if (err) {
        console.log('ERROR')
        res.send('ERROR')
        return;
      }
      res.send({
        eee: req.user,
        hi: 'SECRET test authorization of registered user'
      })
    })
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question