我正在使用NodeJS构建一个基础网站,作为个人学习过程的一部分。
所以我的问题是,我创建了一个基本的用户API,它具有CRUD功能,这是我的create方法。
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!');
}
})
});好的,基本上,我想创建一个控制器来处理登录和注册过程,那么我将如何使用其他路由--即/login --来调用这些路由呢?
所以,理论上,就像这样:
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);
});谢谢你的帮助!
发布于 2015-09-27 15:16:26
用一些代码例子来解释我的想法。
您可以定义此函数:
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);
}
})
})然后,您可以从两个路由处理程序调用它:
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");
});
})您还可以使用承诺来定义处理程序,如果愿意的话可以使用then和catch。
https://stackoverflow.com/questions/32809007
复制相似问题