简体   繁体   中英

Node.js routes authentication

I am quite new to node.js and I am trying to follow a tutorial, and trying to modify the structure of the project. On the tutorial, they have all the endpoints on the server.js file. I have created a folder for models, routes, and controllers. I am using JWT wet tokens.

On the tutorial they have the following code:

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;
   }).catch((e) => {
      res.status(401).send();
   });
  };

app.get ('users/me/', authenticate, (req,res) => {
   res.send(req.user);
});

I have created the following folder structure:
在此处输入图片说明

Here is my authenticate.js code:
在此处输入图片说明

Here is my UserModel.js code:
在此处输入图片说明

Here is my UserRoute.js code:
在此处输入图片说明

Here is my UserController.js code:
在此处输入图片说明

I have no idea how to use how to use my authenticate function inside my controller on export.get_user (in red).

What I need to do or change?

I will recommend you to read this nice article about Express Middleware . Meanwhile you can solve the problem by passing authenticate like below.

UserController.js

// other code  

exports.get_user = function(req, res) {
   res.send(req.user);
}

UserRoute.js

module.exports = function(app) {
    // other code

    app.route('/user/me').get(authenticate, user.get_user);
}

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