Nodejs通过id获取用户

我使用MEAN堆栈的app ,我有用户,我注册和login使用satellizer一切正常。

但是,当我尝试通过它的身份证get用户我什么也没有得到,我可以做请求获取所有用户,但不是通过身份证。

请注意使用Ionicframework作为forntEnd框架。 这里是我的后端的代码:

 app.get('/api/me', function(req, res) { User.findById(req.user, function(err, user) { console.log(req.user); console.log(user); res.send(user); }); }) 

我的前端代码控制器:

 .controller('ProfileCtrl', function($scope, $http, $stateParams, $ionicLoading, $timeout, $stateParams) { $ionicLoading.show({ template: 'Loading...' }); $http.get('http://localhost:3000/api/me') .success(function(data) { console.log("Recived data via HTTP", data); $timeout(function() { $ionicLoading.hide(); $scope.user = data; }, 1000); }) .error(function() { console.log("Error while getting the data"); $ionicLoading.hide(); }); }) 

请求标题:

 Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8,ar;q=0.6,fi;q=0.4,it;q=0.2,en-GB;q=0.2,en-CA;q=0.2 Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1NTAxYjAxMmExMjRlZjIwMTc4M2ExMTQiLCJleHAiOjE0MjcxMzk0NDV9.x9QEdE4E-Vh1SklCheiZqsnJsg8jGzdJnPx2RXeZqS8 Connection:keep-alive Host:localhost:3000 Origin:http://localhost:8100 Referer:http://localhost:8100/ 

你错过了你的服务器调用的重要部分,“ensureAuthenticated”:

 app.get('/api/me', ensureAuthenticated, function(req, res) { User.findById(req.user, function(err, user) { res.send(user); }); }); 

这个卫星实例的ensureAuthenticate是一个非常简单的版本,它只把token.sub的内容放入req.user。 这对于您的查询已经足够了。 通常情况下,在真实应用程序中,将使用护照中间件,将用户加载到中间件中并将其放入req.user。

当使用平均堆栈时,通常req.user被设置为完整的用户对象,即mongoose文档的一个实例。 你想通过IDsearch,所以给查询一个ID:

尝试

 User.findById(req.user._id, function(err, user) { 

代替。

但是,考虑到req.user已经是您正在查询的对象,整个查询可能根本就不需要。

如果你想查找一个不同于authentication的用户,你需要在URLpath中传递你想查询的id,通常是这样的:

 GET /api/users/{id} 

那么你可以使用这个ID

 req.params.id 

并将其传递给findById()调用