[英]ExpressJS Calling Routes within Routes
I'm using NodeJS to build a basic website as part of a personal learning process. 我正在使用NodeJS构建一个基本网站,作为个人学习过程的一部分。
So here's my issue, I've created a basic User API with CRUD functionality, here's my create user method. 所以这是我的问题,我已经创建了具有CRUD功能的基本User API,这是我的create user方法。
app.route('/api/users')
.post(function(request, response) {
var hash = bcryptjs.hashSync(request.body.password, bcryptjs.genSaltSync(10));
var user = new User({
firstname: request.body.firstname,
lastname: request.body.lastname,
email: request.body.email,
password: hash
});
user.save(function(error) {
if(error) {
response.send(error);
} else {
response.send('User Successfully Created!');
}
})
});
Okay, so basically with this I want to create a controller to handle the login and register process, so how would I essentially use other routes ie /login to call these routes? 好的,基本上,我想创建一个控制器来处理登录和注册过程,那么我该如何使用其他路由(即/ login)来调用这些路由?
So, in theory, like this: 因此,理论上来说,像这样:
app.post('/login, function(request, response) {
// call the api method, and pass this request to use in the POST api method
app.call('/api/users/', request.body);
});
Thank you for any help! 感谢您的任何帮助!
Explaining my idea with some code example. 用一些代码示例解释我的想法。
You can have this function defined: 您可以定义以下功能:
function saveUser(request, response, callback) {
var hash = bcryptjs.hashSync(request.body.password, bcryptjs.genSaltSync(10));
var user = new User({
firstname: request.body.firstname,
lastname: request.body.lastname,
email: request.body.email,
password: hash
});
user.save(function(error) {
if(error) {
callback(err);
} else {
callback(null);
}
})
})
Then you can call it from both route handlers: 然后,您可以从两个路由处理程序中调用它:
app.route('/api/users').function(function(req, res) {
saveUser(req, res, function() {
return res.json({success: true});
});
})
app.post('/login').function(function(req, res) {
saveUser(req, res, function() {
return res.render("some_view");
});
})
You can also use Promises to define the handler, to use then
and catch
if you like. 您还可以使用Promises定义处理程序,
then
使用then
并根据需要进行catch
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.