node.js - 如何将结果从模型返回到nodejs中的控制器
问题描述
我是第一次使用 node js。我的 nodejs 项目采用 MVC 风格,我正在做 Ajax 登录请求。但我没有从模型中获取数据......这是代码......
控制器/Auth.js
var data = req.body;
Auth_model.login(data, function(err,result){
if(!result){
response = {
error:true,
message : "Username or Password is wrong."
};
res.send(JSON.stringify(response));
}else{
response = {
error:false,
message : "Logged in Successfully."
};
// console.log(result);
res.send(JSON.stringify(response));
}
});
});
模型 / Auth_model.js
module.exports.login = function(data, callback){
var email = data.email;
var password = data.password;
var sql = 'SELECT * FROM `users` WHERE email='+mysql.escape(email);
db.query(sql, callback,function (err, result, fields) {
if (result) {
bcrypt.compare(password,result[0].password, function(err, result) {
if(result){
return result;
}else{
return err;
}
});
}
});
}
解决方案
控制器/Auth.js
var data = req.body;
// here you are passing your callback function as second argument
// So, you can use it in your login model when you get your response
Auth_model.login(data, function(err,result){
.........
}
模型 / Auth_model.js
module.exports.login = function(data, callback){
.......
if(result){
// use your callback function pass error : null and result:result
callback(null,result);
}else{
callback(err,null)
}
......
}
您也可以使用 promise 而不是回调函数
module.exports.login = (data) = new Promise(function(resolve, reject) {
.......
if(result){
// use your callback function pass error : null and result:result
resolve(result);
}else{
reject(err);
}
......
});
// use it like :
login(data).then(result=>console.log(result)).catch(err=>console.log(err))
了解更多关于回调函数和 Promise 的信息。
推荐阅读
- java - 如何在android app中实现滑动功能
- installation - Azure Functions 的分发
- sql - 按值仅计算每个组的百分比
- python - 如何将列中的逗号分隔值替换为另一个完全匹配的数据框中的值?
- javascript - 有没有办法在 AR.JS 中进行字符串插值?
- python-requests - 如果匹配[best_match_index]:IndexError:列表索引超出范围,该怎么办
- javascript - Node JS:基于城市的JSON重构
- php - MySQL 在 datetime 列的先前保存值中添加 365 天
- python - UE4 与 Python 机器人框架测试
- docker - docker 找不到本地创建的图像