2015-09-16 44 views
0

我有一個相當簡單的方法奮力登錄到服務器,後來以確保我仍然登錄,我發送一個GET請求來接收我的用戶名。我正在使用一個小的node.js服務器和使用JQuery的單個頁面對象。Node.js的登錄

// prints User name to the console if logged in 
function getUserName() { 
    $.ajax({ 
     url: "http://localhost:4730/login", 
     type: "GET", 
     dataType: "json", 
     success: function (resJson) { 
      $.each(resJson, function (i, userName) { 
       console.log(userName); 
      }); 
     }, 
     error: function (xhr, status) { 
      console.log("Sorry, there was a problem!"); 
     } 
    }); 
} 

// login a known user 
function login(name, password) { 
    var userData = { 
     name: name, 
     password: password 
    }; 

    $.ajax({ 
     url: "http://localhost:4730/login", 
     type: "POST", 
     dataType: "json", 
     data: userData, 
     error: function (xhr, status) { 
      console.log("Sorry, there was a problem!"); 
     }, 
     complete: function (xhr, status) { 
      console.log(xhr); 
     } 
    }); 
} 

我的服務器(的node.js)正在產生僞用戶標識,並檢查這個時候下GET請求到達。

// Checks if the user is logged in and returns its name or an empty string 
app.get('/login', function (req, res) { 
    if (typeof (req.session.user_id) == "number") { 
     res.json(users[req.session.user_id].name); 
     return; 
    } 
    res.json(""); 
}); 

// Check if the user exists and if the password is correct 
app.post('/login', function (req, res) { 
var post = req.body; 
var user = findUser(post.name); 
if(!!user && post.password == user.password) 
    {  
     req.session.user_id = user.id;  
     res.json(true);  
     return; 
    } 
    res.json(false); 
}); 

我的用戶已經註冊並且登錄請求成功返回。但是登錄後,我的GET請求getUserName返回一個空字符串。我沒有得到的是session.user_id在哪裏設置?客戶不是現在呢?

我已經用護照等,但我想了解的會話/用戶ID處理基本看到夫婦的解決方案。

非常感謝您的幫助

回答

0

這裏:

var post = req.body; // the request body with username & password. 
var user = findUser(post.name); // you are extracting the username 
if(!!user && post.password == user.password) 
    //---------------------------^^^^^^^^^^^^^-----this isn't available in it. 

  1. 在你var post你把所有的發佈請求體,它具有名稱&密碼。
  2. 在你var user你貼出來的值提取名稱。
  3. 現在,在您if的病情,我不認爲user.password可用。

要麼確保你會從findUser(post.name)返回對象或將其更改爲:post.password != ""

+0

喜潔,非常感謝您的回覆。我應該提到,我的用戶已經註冊並且密碼的比較是成功的。在我看來,我的客戶現在不其用戶ID,它是在這裏分配:'req.session.user_id = user.id;'再次感謝。 – Smii