简体   繁体   中英

node.js authenticate middleware

I've a small issue with a declaration of a function as middleware. I've the feeling that I'm missing something small but am now stuck.

The declaration is in a Routerfile:

var {authenticate} = require('./middleware/authenticate');

module.exports = function(app) {
  var users = require('../controllers/userController');

  app.route('/users')
    .post(users.createUser);

  app.route('/users/me')
    .get(users.getMe, authenticate);

  app.route('/users/me/token')
    .delete(users.logout, authenticate);

  app.route('/users/login')
    .post(users.login);
};

This is giving an error like:

Subsequent variable declarations must have the same type.  Variable 'authenticate' must be of type '(req: any, res: any, next: any) => void', but here has type 'any'.

The authenticate file looks like:

var {User} = require('./../api/models/user');

var authenticate = (req, res, next) => {
  var token = req.header('x-auth');
  User.findByToken(token).then((user) => {
    if (!user) {
      return Promise.reject();
    }

    req.user = user;
    req.token = token;
    next();
  }).catch((e) => {
    res.status(401).send();
  });
};

module.exports = {authenticate};

I think I'm close but can't figure it out.

Try this:

Note: Middleware always comes before the controller function call.

app.route('/users/me')
    .get(authenticate, users.getMe);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM