简体   繁体   English

将变量从JavaScript传递到Node.js

[英]Pass variables from JavaScript to Node.js

I have a simple HTML like this: 我有一个像这样的简单HTML:

<html>
    <head><title></title></head>
    <body>
        <script>var testVariable = "Hello"</script>

        <form method="post" action="/">
            <input type="submit" name="submit" value="Submit">
        </form>
    </body>
</html>

And my Node.js looks like this: 我的Node.js看起来像这样:

app.post('/', function(req, res) {
    Console.log(req.body.testVariable);
});

What I need to do is when the form is submitted the testVariable needs to be passed to the Node.js function, I'm trying with hidden fields but I'm still having problems with that, ie: 我需要做的是在提交表单时,将testVariable传递给Node.js函数,我正在尝试使用隐藏字段,但是仍然存在问题,即:

<input type="hidden" name="chat" value="<script>testVariable</script>">

But as you can imagine it pass all the script as a string, and not the value of the variable. 但是可以想象,它将所有脚本作为字符串而不是变量的值传递。

Does someone knows how to do that? 有人知道该怎么做吗? Sorry if this is a silly question, I'm new to JavaScript and Node.js in general and I can't find answers in Google. 抱歉,如果这是一个愚蠢的问题,我是JavaScript和Node.js的新手,我在Google中找不到答案。

Thanks. 谢谢。

-----EDIT------ - - -编辑 - - -

My form now looks like this: 我的表格现在看起来像这样:

<form method="post" action="/">
    <input type="hidden" name="chat" id="hiddenInput" />

    <script>
        var input = document.getElementById('hiddenInput');
        input.value = $('#conversation');
    </script>

    <input type="submit" name="submit" value="Submit">
</form>

And on my Node.js I'm printing the object like this: 在我的Node.js上,我像这样打印对象:

console.log(JSON.stringify(req.body.chat));

and it prints "[object Object]" (including the quotes). 并显示"[object Object]" (包括引号)。

I verified that the variable received is a string with: 我验证了接收到的变量是一个字符串,其中包含:

console.log(typeof req.body.chat);  // prints "string"

Use javascript to target the hidden input and set the value before submitting the form: 在提交表单之前,请使用javascript定位隐藏的输入并设置值:

HTML 的HTML

<input type="hidden" name="chat" id="hiddenInput" />

JS JS

var input = document.getElementById('hiddenInput');
input.value = testVariable.toString();

Also, on your Node server, you need to access req.body.chat - the body property you want corresponds to the name of the input element 另外,在您的Node服务器上,您需要访问req.body.chat您想要的body属性对应于输入元素的name

You need to use the input name attribute. 您需要使用输入name属性。 And that input must be inside the form so you can catch it in Node: 该输入必须在form内部,以便您可以在Node中捕获它:

<input type="hidden" name="testVariable" value="the value string">

Try: 尝试:

    <form method="post" action="/">
        <input type="hidden" name="testVariable" value="the value string">
        <input type="submit" name="submit" value="Submit">
    </form>

And it should log "the value string" in Node. 并且应该在节点中记录"the value string"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM