gpt4 book ai didi

javascript - 使用
、jQuery、Sequelize 和 SQL 进行登录和路由

转载 作者:行者123 更新时间:2023-12-01 03:11:02 27 4
gpt4 key购买 nike

我的目标是当用户单击提交按钮时,在 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");
}
});
});

登录.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 专家,也从未使用过它,但快速Google search显示第二个参数作为查询字符串传递,这就是 GET 应该如何工作。如果您有任何数据要发送,请通过查询字符串发送,而不是通过请求正文。

因此,您遇到的问题在于服务器端代码,您从正文而不是查询字符串中读取用户名密码。因此,为了使其正常工作,您需要从像这样的查询中提取用户名和密码(我猜您正在使用 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");
}
});
});

我希望您了解流程以及您的错误在哪里。

关于javascript - 使用 <Form>、jQuery、Sequelize 和 SQL 进行登录和路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45853237/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com