如何使用HTML和nodejs显示用户名



所以,我正在构建一个简单的登录页面,我想在您成功登录该页面后显示用户名。但我有点困惑如何在HTML中做到这一点。我在ejs、angular、react和passport上看到了很多材料。但我没有用它。我只是使用简单的HTML、CSS和NodeJS来构建它。因此,如果有人能在这方面帮助我,我将不胜感激。

所以我登录后的HTML页面:

<!DOCTYPE html>
<head>
</head>
<body>
Hi user. //want to show the username here
<form name="logout" method="post" action='/logout'>
<label class="logoutLblPos">
<input name="submit2" type="submit" id="submit2" value="log out">
</label>
</form>
</body>

以及我在server.js文件中成功登录的代码:

app.post("/login", urlencodedParser, async (req, res) => {
const { email, password } = req.body;
db.query(
"SELECT * FROM users WHERE email = ?",
[email],
async (error, result) => {
if (error) {
console.log(error);
} else {
try {
if (result.length === 0 || !result) {
res.json({ message: "Email has not been registered" });
} else {
bcrypt.compare(password, result[0].PASSWORD, (err, results) => {
if (err) {
console.log(err);
return res.json({
message: "there has been some problem matching the password",
});
} else {
if (results) {
//token creation

const id = result[0].ID;
console.log(id)
const token = jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN,
});
console.log("the token is " + token);
const cookieOptions = {
expires: new Date(
Date.now() +
process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
),
httpOnly: true,
};
res.cookie("myCookieJwt", token, cookieOptions)
res.status(200).redirect("/user");
} else {
res.json({ message: "Please enter correct password" });
}
}
});
}
} catch (error) {
console.log(error);
return;
}
}
}
);
});

您需要使用某种库来向端点发出POST请求。JQuery Ajax来拯救,你可以使用其他库,如Axios以及

$.ajax({
type: 'POST',
url: "/login",
data: "FORM DATA",//<---- Form Data (username,password)
dataType: "text or JSON", //<-- Whichever you are using
success: function(resultData) { $('#username').text(resultData.username); } //<-- I'm assuming username is coming in
});

您需要从node.js端点返回username,然后可以动态设置div或任何其他HTML标记的文本。

这个例子可能需要调整,因为它可能无法开箱即用,但它会让你走上正确的道路。

最新更新