2015-08-27 54 views
7

我使用Node與Express.js並嘗試使用JWT進行身份驗證,在用戶登錄後生成一個令牌,並將其保存到localstorage,但我不知道如何獲取認證令牌。 這是使用代碼IM:保存並從本地存儲獲取快速js令牌

登錄觀點:

$.ajax({ 
      type: 'POST', 
      url: base_url + "login", 
      data: postData, 
      dataType: 'json', 
      success: function(data){ 
       // console.log(data1); 
       // alert(data); 
       _(data); 
       if(data.success === false){ 
        showError(data.msg); 
       }else{ 
        showError(data.msg); 
        window.localStorage.setItem("authToken", data.token); 

        var token = window.localStorage.getItem('authToken'); 
        if (token) { 
         $.ajaxSetup({ 
         headers: { 
          'x-access-token': token 
         } 
         }); 
        } 
       } 
      } 
     }); 

這是使用之前的任何路由的檢查路線認證IM是訪問:

router.use(function(req, res, next){ 
    var token = req.headers['x-access-token']; 
    console.log(token); 
    if (token) { 
     // verifies secret and checks exp 
     jwt.verify(token, app.get('superSecret'), function(err, decoded) {  
      if (err) { 
       return res.json({ success: false, message: 'Failed to authenticate token.' });  
      }else{ 
       // if everything is good, save to request for use in other routes 
       req.decoded = decoded;  
       next(); 
      } 
     }); 

     } else { 

     // if there is no token 
     // return an error 
     return res.status(403).send({ 
      success: false, 
      message: 'No token provided.' 
     }); 
     } 
}); 

控制檯.log(令牌)我得到一個未定義的變量,好像我不知道如何從路由訪問令牌。非常感謝。

+1

您是否驗證(通過瀏覽器的開發者工具)的頭實際上是被髮送? – mscdex

+0

@mscdex當我在網絡上時,我無法看到x-access-token作爲請求標題,或者作爲響應標題 – user3334406

回答