我正在努力使用一种相当简单的方法登录服务器,然后确保我仍然登录,我正在发送GET请求以接收我的用户名。我正在使用一个小的node.js服务器和一个使用JQuery的单个页面对象。
// 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)正在生成一个虚拟用户ID,并在下一个GET请求到达时检查这个用户ID。
// 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);
});
我的用户已注册,登录请求成功返回。但登录后,我对getUserName的GET请求返回一个空字符串。我没有得到的是session.user_id设置在哪里?客户不是现在必须吗?
我已经通过使用护照等看过几个解决方案,但我想了解会话/用户ID处理的基本知识。
非常感谢你的帮助
答案 0 :(得分: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.
var post
中,您拥有所有已发布的请求正文,其中包含姓名&密码。var user
中,您要从已发布的值中提取名称。if
状态我不认为user.password
可用。要么确保从findUser(post.name)
返回对象,要么将其更改为:post.password != ""