skip to Main Content

How can i display a variable from a node.js route in a HTML File?

i have a node.js route like:

router.post("/login", async (req,res) => {
    try {
        const formData = req.body
        const name = formData.name
        const pass = formData.password
        const checkUser = await user.findOne({name: name})
        const checkPass = await user.findOne({password: pass});
      
        if(checkUser && checkPass){
            session=req.session;
            session.userid=req.body.name;            
            console.log(session.userid);
            //res.send("Welcome User <a href='/logout'>click to logout</a>");
            res.sendFile(path.resolve(__dirname, '../public/admin.html'));
        }
        else{
          res.send(`Use not registered`);
            console.log(name)
        }
      }catch(err){
        console.log(err)
      }
})

i want to display the session.userid in my HTML file. How can i access the variable in noide.js?

in the top of my node.js file i have a variable var session;

and in my HTML file i have the script:

<script>
      function setUsername() {
      var number = "username";
      document.getElementById("username").innerHTML = session.userid;
    }
</script>

how can i set the var number = session.userid in order to display the logged name in html?

2

Answers


  1. I’d look up EJS. Its basically HTML with a little more syntax to to embedded JavaScript operations. You can serve EJS files from an Express server the exact same way as HTML files, but you can also pass props and access the variables in the EJS file.

    Alternatively, you can make pass your session id to the client via a client cookie with cookie-session. Just make sure httpOnly is false so that JavaScript on the client can access the cookie

    Login or Signup to reply.
  2. In your ../public/admin.html insert above your script:

    <script name="backend-data"></script>
    

    Then insert your session variable serialized with JSON which is also JS object literal in your case:

    import fs from 'fs';
    router.post("/login", async (req,res) => {
        try {
            const formData = req.body
            const name = formData.name
            const pass = formData.password
            const checkUser = await user.findOne({name: name})
            const checkPass = await user.findOne({password: pass});
          
            if(checkUser && checkPass){
                session=req.session;
                session.userid=req.body.name;            
                console.log(session.userid);
                //res.send("Welcome User <a href='/logout'>click to logout</a>");
                
                let html = fs.readFileSync(path.resolve(__dirname, '../public/admin.html').toString();
                html = html.replace(/(?<=script name="backend-data">)(?=<)/, 
                    () => `var session = ${JSON.stringify(session};`));
                res.send(html);
            }
            else{
              res.send(`Use not registered`);
                console.log(name)
            }
          }catch(err){
            console.log(err)
          }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search