2017-09-04 68 views
0

我正在用MEAN Stack構建一個Web應用程序。我試圖實現的是,當用戶登錄他的用戶信息時,我的REST API會被Angular獲取。我設置了API路由http://localhost:3000/api/user/profile,它應該用包含用戶對象的json響應。Angular 4&Passport API身份驗證

router.get('/user/profile', function(req, res, next){ 
    //console.log(req); 
    if(req.user === undefined){ 
     res.json({ 
      success: false, 
      msg: 'Unautorized' 
     }); 
    } else { 
     res.json({ 
      success: true, 
      user: { 
       id: req.user.steam.id, 
       name: req.user.steam.name, 
       avatar: req.user.steam.avatar, 
       avatarmedium: req.user.steam.avatarmedium, 
       avatarfull: req.user.steam.avatarfull 
      } 
     }); 
    } 
}); 

當角用戶登錄啓動一個GET請求:

ngOnInit() { 
    this.authService.getProfile().subscribe(profile => { 
     this.user = profile.user; 
     console.log(profile); 
    }, 
    err => { 
     console.log(err); 
     return false; 
    }); 

} 

getProfile():

getProfile(){ 
    return this.http.get('http://localhost:3000/api/user/profile') 
    .map(res => res.json()); 
} 

當我加載了我的網站,登錄,轉到配置文件頁面返回的對象包含成功:false和消息'未經授權'而不是用戶對象。這是爲什麼發生?

+0

您在this.http.get調用中沒有發送任何參數。訪問參數的方式也是錯誤的。請參閱此問題以獲取發送參數和獲取參數的正確格式。 https://stackoverflow.com/questions/17007997/how-to-access-the-get-parameters-after-in-express –

+0

我不認爲你正確理解我的問題,對不起,如果我沒有說得好。 get請求正在完全工作,我只是得到了req.user未定義即使我已登錄的情況下的響應。當訪問route/api/user/profile和req.user時,我console.logged req從角度進行調用時某個對象不存在。因此,不知何故,登錄時Cookie不會被設置。 – DerJP

+0

通常,用戶信息通過授權標頭中的身份驗證令牌傳遞到服務器。用戶驗證後,您應該從auth提供商處收回令牌。這個標記最有可能是一個jwt,如果你通過一個頭傳遞迴服務器,你可以解碼jwt令牌並獲取它的信息。如果您確實需要使用https://jwt.io/上的調試器來查看其中的所有信息。如果你在github中有這個,將會更容易排除故障:) – zmanc

回答

0

我完全重新設計了我的方法。我實現了json web令牌,它現在通過url參數向用戶發送一個令牌(包含所有用戶數據)。