Nodejs通过id获取用户

Nodejs get user by id

我正在为 app 使用 MEAN 堆栈,我有用户使用 satellizer 注册和登录,一切正常。

但是当我尝试 get 通过其 ID 访问用户时,我什么也得不到,我可以请求获取所有用户,但不能通过 ID。

注意我使用 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();
        });
})

请求Header:

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 文档的一个实例。你想按 id 搜索,所以给查询一个 id:

尝试

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

相反。

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

如果你想查找与认证用户不同的用户,你需要在URL路径中传递你想查询的id,通常是这样的:

GET /api/users/{id}

然后你可以使用

得到这个id
req.params.id

并将其传递给 findById() 调用