英文:
How to access a varible from an node.js in HTML file?
问题
我想在我的HTML文件中显示session.userid
。如何在Node.js中访问该变量?
在我的Node.js文件顶部,我有一个变量var session;
在我的HTML文件中,我有以下脚本:
<script>
function setUsername() {
var number = "username";
document.getElementById("username").innerHTML = session.userid;
}
</script>
如何设置var number = session.userid
以便在HTML中显示已登录的用户名?
英文:
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?
答案1
得分: 0
我会查看EJS。它基本上是带有一些额外语法的HTML
,用于嵌入JavaScript操作。您可以像HTML
文件一样从Express
服务器提供EJS
文件,但您还可以传递属性并访问EJS文件中的变量。
或者,您可以通过cookie-session将您的会话ID
传递给客户端的客户端cookie
。只需确保httpOnly
为false,以便客户端的JavaScript可以访问cookie。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论