0

How do I store HTML form inputs inside a variables in Node JS. Where am I going wrong? Here is my HTML form

<form action="localhost:8080/api/aa" method="post">
    <input id="host"  type="text" placeholder="Enter Host Name" > <br/>
    <input id="port" type="text" placeholder="Enter Port" ><br/>
    <input type="submit" value="Submit">
</form>

And my node app where I need my form inputs assigned to the variables test.jsstrong text

var port        = process.env.PORT || 8080; 
var router      = express.Router();

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

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

app.use('/api', router);

router.post('/aa', function(req, res){ 
    hostname = req.body.hostname;
    port2 = req.body.port2;
    console.log(res);
    console.log(hostname);
    console.log(port2);   
});
url ="mongodb://"+hostname+":"+port2;
console.log(url); 

app.listen(port);
console.log('Listening at port ' + port);
console.log(url);

Not sure if my form inputs are being correctly handled. The submission of form doesn't reflect the values entered in form on to the Node JS variables

1 Answer 1

1

Where are hostname and port2 defined in the HTML form? The keys should be defined by the name attribute:

<form action="localhost:8080/api/aa" method="post">
    <input id="host" name="hostname"  type="text" placeholder="Enter Host Name" > <br/>
    <input id="port" name="port2" type="text" placeholder="Enter Port" ><br/>
    <input type="submit" value="Submit">
</form>

Be aware that your Node global variables will be shared by all your users.

Sign up to request clarification or add additional context in comments.

9 Comments

It is still not taking the input values.
Any log? Can your log req.body?
console.log(req.body) returns nothing. Could you check if the endpoints are correct?
Can you check the inspector o your browser to check if the request is being sent correctly? If so, any status code of the response?
Status says it was cancelled
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.