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
I’d look up EJS. Its basically
HTML
with a little more syntax to to embedded JavaScript operations. You can serveEJS
files from anExpress
server the exact same way asHTML
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 aclient cookie
with cookie-session. Just make surehttpOnly
is false so that JavaScript on the client can access the cookieIn your ../public/admin.html insert above your script:
Then insert your session variable serialized with JSON which is also JS object literal in your case: