【发布时间】:2016-01-22 06:44:51
【问题描述】:
我的 nodejs API 应用中有这条路线:
router.post('/user', function(req, res, next){
if(!req.body.username){
return res.status(400).json({message: 'Geen username'});
}
var user = {};
User.find({ 'username': req.body.username}, function(err, foundUser){
if(err)
return next(err);
if (foundUser) // check the value returned for undefined
{
user = foundUser;
}
});
res.json(user);
});
但是这只是返回 {},我确定用户名在数据库中。
这就是我在 Angular 应用程序中调用路线的方式:
$scope.user = function() {
$http({
method: 'POST',
url: "http://groep6api.herokuapp.com/user",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
//'authentication': 'bearer' + $window.localStorage.getItem('token')
},
data: {username: $window.localStorage.getItem('username')},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).success(function (result) {
console.log(result);
}).error(function(){
});
};
我对 Angular 和 Nodejs 还很陌生,我尝试过 User.find 和 User.findOne,但都没有奏效。如何根据参数在 mongoose 中搜索对象?
【问题讨论】:
-
你在用护照吗?
-
无需将其保存在使用数据库的本地存储中...
-
试试这个:
User.findOne({ 'username' : req.body.username }, -
我很确定你的 if 语句有问题。你能删除 if(foundUser) 我很确定这是问题所在
-
您的
res.json需要进入查询回调。否则,您将在查询结果可用之前发送响应。
标签: angularjs node.js mongoose