2015-03-13 85 views
1

我正在使用MEAN棧的app,我有用戶註冊並使用satellizer登錄,一切正常。Nodejs通過編號獲取用戶

但是,當我嘗試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(); 
     }); 
}) 

請求頭:

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/ 
+0

什麼'req.user'的'User.findById'調用之前的值? – JohnnyHK 2015-03-13 19:08:53

+0

它是未定義的 – 2015-03-13 19:27:49

回答

2

你錯過了一個重要的組成部分的服務器調用,「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設置爲完整用戶對象,即貓鼬文檔的實例。你想通過ID進行搜索,這樣就給查詢一個id:

嘗試

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

代替。

但是,考慮到req.user已經完全是您要查詢的對象,整個查詢可能根本就不需要。

如果你想查找比驗證一個不同的用戶,你需要傳遞要在URL路徑查詢ID,通常是這樣的:

GET /api/users/{id} 

那麼你就可以得到這個ID使用

req.params.id 

,並把它傳遞給findById()呼叫

+0

我試過了,我得到這個錯誤無法讀取undefined – 2015-03-13 19:29:06

+0

屬性'_id'好吧,這意味着,你沒有通過身份驗證。 req.user未定義是護照告訴你沒有登錄用戶的方式。對於RESTFul API,您需要在每次調用時都傳遞憑據,通常通過在$ http – Reto 2015-03-13 19:30:32

+0

上設置auth頭文件來完成,但是如果沒有進行身份驗證。如何在註冊後在我的db中找到用戶。 – 2015-03-13 19:36:11