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 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.