如何从HTML文件中访问Node.js中的变量?

huangapple go评论74阅读模式
英文:

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(&quot;/login&quot;, async (req,res) =&gt; {
    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 &amp;&amp; checkPass){
            session=req.session;
            session.userid=req.body.name;            
            console.log(session.userid);
            //res.send(&quot;Welcome User &lt;a href=\&#39;/logout&#39;&gt;click to logout&lt;/a&gt;&quot;);
            res.sendFile(path.resolve(__dirname, &#39;../public/admin.html&#39;));
        }
        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:

&lt;script&gt;
      function setUsername() {
      var number = &quot;username&quot;;
      document.getElementById(&quot;username&quot;).innerHTML = session.userid;
    }
&lt;/script&gt;

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

huangapple
  • 本文由 发表于 2023年6月30日 02:18:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583683.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定