简体   繁体   English

如何在 Node JS 变量上存储 HTML 表单输入?

[英]How do I store HTML form inputs on a Node JS variable?

I am unable to set the values of HTML form inputs on to my Node JS variable.我无法将 HTML 表单输入的值设置到我的 Node JS 变量中。 Below is my JS code where I am not able to set the values of variables "hostname" and "port" which will in turn concatenate to a new variable called url.下面是我的 JS 代码,其中我无法设置变量“主机名”和“端口”的值,这将依次连接到一个名为 url 的新变量。

console.log(url) prints just mongodb://:. console.log(url) 只打印 mongodb://:。 which suggests that my HTML form values are not being stored in my Node JS variables.这表明我的 HTML 表单值没有存储在我的 Node JS 变量中。

var express     = require('express');        // call express
var app         = express();                 // define our app using express
var bodyParser  = require('body-parser');
var router      = express.Router();  

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        

var router = express.Router();              

const dbname    = "admin";

var hostname ='';
var port2 ='';

app.post('/', function(req, res){ 
    hostname = req.body.hostname;
    port2 = req.body.port2;
});

var url ="mongodb://"+hostname+":"+port2;

Below is my html which is handling the form inputs下面是我的 html 处理表单输入

    <form class="clr-form" action="/" method="POST">
        <input type="text" name="hostname" placeholder="Enter Host Name" class="clr-input"> <br/>
        <input type="text" name="port2" placeholder="Enter Port" class="clr-input"><br/>
        <input type="submit" value="Submit" />
    </form>

You don't need to redeclare the port2 again您不需要再次重新声明 port2

var port2 ='';

app.post('/', function(req, res){ 
    var hostname = req.body.hostname;
    port2 = req.body.port2;
});

var url ="mongodb://"+hostname+":"+port2;
var hostname ='';
var port2 ='';

app.post('/', function(req, res){ 
     hostname = req.body.hostname;
     port2 = req.body.port2;
});

You should not declare variables inside the function again if you want to assign body values to your variables which one you will be using outside of scope.如果要将主体值分配给将在 scope 之外使用的变量,则不应再次在 function 中声明变量。

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

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