[英]Using <Form>, jQuery, Sequelize and SQL to Login and route
我的目标是当用户单击提交按钮时,以html形式使用ID#username-l和#pwd-l的值,让它们将这些值与SQL数据库中的值进行比较,如果这些值与值完全相同在数据库中,然后将用户路由到指定的路由(目前,仅/ user可以进行测试)。 目前它路由到/? 没有任何未指定的错误。 控制台显示查询正在返回用户名= null和密码= null。 我在数据库中有种子,称为用户名=测试密码=测试进行测试。 任何帮助表示赞赏!
HTML:
<form id="login-form">
<div class="form-group">
<label for="username-l">Username:</label>
<input type="username" class="form-control" id="username-l" placeholder="Enter username">
</div>
<div class="form-group">
<label for="pwd-l">Password:</label>
<input type="password" class="form-control" id="pwd-l" placeholder="Enter password">
</div>
<button id="login-button" type="submit" class="btn btn-default">Login</button>
</form>
排序:
app.get("/api/users", function(req, res) {
db.User.findAll({
where:
{
username: req.body.username,
password: req.body.password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (req.body.username === dbUser.username && req.body.password === dbUser.password) {
res.redirect("/users");
} else {
console.log("error");
}
});
});
LOGIN.JS:
$("#login-button").on('click', function() {
var username = $("#username-l").val().trim();
var password = $("#pwd-l").val().trim();
$.get("/api/users", function(data){
console.log(data);
if (username === data.username && username === data.password) {
reRoute();
} else {
console.log("that does not exist");
}
});
});
function getUser(userData) {
$.get("/api/users", userData).then(reRoute());
}
function reRoute() {
window.location.href = "/users";
}
首先,您正在执行GET
请求,就我所知HTTP而言,该请求没有正文。 其次,我不是jQuery的专家,也从未使用过它,但是谷歌的快速搜索显示第二个参数作为查询字符串传递,这就是GET
应该起作用的方式。 如果您有任何要发送的数据,则通过查询字符串而不是通过请求正文发送。
因此,您遇到的问题是服务器端代码,您在其中从主体而不是从查询字符串读取username
和password
。 因此,为了使其正常工作,您需要像这样从查询中提取用户名和密码(我猜您正在使用Express):
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
// do the rest of the stuff with Sequelize and bussiness logic here
});
在旁注中,您对路由器的完整回调有一些不好的事情,例如冗余检查用户名和密码是否与从数据库中检索到的用户名和密码匹配。 您已经要求Sequelize从数据库中检索一行,其中用户名和密码是您从前端获取的用户名和密码,因此,您无需检查实例的用户名和密码是否与您拥有的用户名和密码匹配。 您需要检查实例是否为null
,因为这意味着您的数据库中没有使用该用户名和密码的用户。 因此,“固定”代码应如下所示:
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
db.User.findAll({
where: {
username,
password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (dbUser != null) {
res.redirect("/users");
} else {
// you'd maybe like to set response status to 404
// also some user friendly error message could be good as response body
console.log("Error: user not found");
}
});
});
我希望您对流程有所了解,并且您的错误在哪里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.