我正在为我的单页应用程序使用 javascript MEAN 堆栈。
我有一个 Angular 工厂正在调用我的 Api。
app.factory('authorizing', function($resource){
return $resource(
'/api/authorizing/:username',
{'username':'@username'},
// retreiving only one user and all their roles
{'singleUser' : {
method:'GET'
,isArray: false
}}
);
});
我像这样在 Controller 中调用工厂。我的目标是根据从 Api 返回的响应来更新网页数据。我期望返回一个 true 或 false 值。我尝试过其他方法,但我想在服务器端保留我的授权。
app.controller('usrPageController', function ($scope, usrServiceById, $route, authorizing, $rootScope) {
$scope.updateUser = function (data,field){
var vCheckUserRoles;
vCheckUserRoles = authorizing.singleUser({'username': $rootScope.current_user});
if (vCheckUserRoles == true){
usrServiceById.update({'username':username},{field:data, 'fieldName':field});
};
};
});
数据库使用res.send返回结果数据。
.get(function (req, res) {
RoleUser.find({ 'aclUserName': req.params.username }, function (err, aclUser) {
if (err) { return res.sendStatus(500) };
// return an error if no user is found
if (aclUser == null) { return res.sendStatus(401) };
//check for proper role in list of users
for (var i = 0; i < aclUser.length; i++) {
if (aclUser[i].aclUserResource == req.params.username + '_PROFILE') {
//return a successful status
return res.send('true');
};
};
//return a failed status
return res.send('false');
});
});
我没有从代码中得到任何错误,但是当它在 res.send 之后到达 Controller 时,返回对象为空。我尝试过返回不同类型的数据,但似乎没有任何效果。任何帮助表示赞赏。我的 Api 中有其他 res.send 调用。它们可以工作,但我通过回调直接从数据库获取数据并将其提供给 res.send。这是我的代码中唯一一次尝试返回除成功回调变量之外的其他内容。
更新的代码:
我删除了 var vCheckUserRoles。现在该值已传递给成功回调
app.controller('usrPageController', function ($scope, usrServiceById, $route, authorizing, $rootScope) {
authorizing.singleUser({'username': $rootScope.current_user},function(response){
console.log('response = ' + response.data)
if (response.data == 'true'){
usrServiceById.update({'username':usrSingle.username},{field:data, 'fieldName':field});
};
});
});
最佳答案
您可以使用 res.json 而不是 res.send 来发送查询状态。
示例//// res.json({status:true})
在客户端,您可以访问 data.status 字段中的状态值。
关于javascript - 如何从 api res.send 检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35470533/