[英]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. 我对node.js相当陌生,我试图遵循一个教程,并试图修改项目的结构。 On the tutorial, they have all the endpoints on the server.js file.
在本教程中,它们的所有端点都在server.js文件中。 I have created a folder for models, routes, and controllers.
我已经为模型,路线和控制器创建了一个文件夹。 I am using JWT wet tokens.
我正在使用JWT湿令牌。
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: 这是我的authenticate.js代码:
Here is my UserModel.js code: 这是我的UserModel.js代码:
Here is my UserRoute.js code: 这是我的UserRoute.js代码:
Here is my UserController.js code: 这是我的UserController.js代码:
I have no idea how to use how to use my authenticate function inside my controller on export.get_user (in red). 我不知道如何在export.get_user(红色)上的控制器内使用身份验证功能。
What I need to do or change? 我需要做什么或更改?
I will recommend you to read this nice article about Express Middleware . 我建议您阅读这篇有关Express Middleware的不错的文章。 Meanwhile you can solve the problem by passing
authenticate
like below. 同时,您可以通过如下所示的
authenticate
来解决问题。
UserController.js UserController.js
// other code
exports.get_user = function(req, res) {
res.send(req.user);
}
UserRoute.js UserRoute.js
module.exports = function(app) {
// other code
app.route('/user/me').get(authenticate, user.get_user);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.