0

So, I am building a simple login page and I wanna show the username after you succesfully login to the page. But I am kind of confused how to do that in HTML. I saw lots of materials on ejs and angular and react and passport. But I am not using that. I am just using simple HTML,CSS and NodeJS to build this. So, if someone can help me regarding this, I will be much obliged.

So my HTML page after I login:

<!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>

and my code for successful login in server.js file:

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;
        }
      }
    }
  );
});

1 Answer 1

1

You need to use some kind of library that make POST request to the endpoint. JQuery Ajax to rescue, you can use other libraries like Axios as well

$.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
});

you need to return username from node.js endpoint then You can set the text of div or any other HTML tag dynamically.

This example might need a tweaking as it might not work out of the box, but it will set you on correct path.

Sign up to request clarification or add additional context in comments.

2 Comments

should I include this in my server.js file or in html file? never used ajax before so just asking.
Generally you make a separate file because this logic is for frontend (HTML) and you can use that file using <script> tags to import it into your HTML file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.