ExpressJS呼叫路由中的路由
我正在使用NodeJSbuild立一个基本的网站,作为个人学习过程的一部分。
所以这是我的问题,我创build了一个基本的用户API与CRUDfunction,这里是我的创build用户方法。
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!'); } }) });
好吧,基本上这样我想创build一个控制器来处理login和注册过程,那么我将如何使用其他路线,即/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); });
感谢您的任何帮助!
用一些代码示例来解释我的想法。
你可以定义这个function:
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"); }); })
你也可以使用Promise定义处理程序, then
使用,如果你喜欢的话。