Way to know when a form button is clicked, and then collect all of the form values and use them in Node.JS

Viewed 85

So, lets say i had a form on my website like a signup form, and I had a signup button, how could I get the values for each of the form's fill in boxes(username, email and password boxes) and then get those values in NodeJS to add it to a mongodb and hash the password etc., I just need to know how I can get the button click event and then the values for the boxes, I also wish to check if every box is filled in beforehand, so I can update the site to say "Please fill in all of the boxes" using JavaScript.

I hope this explains my question.

2 Answers

just before the click event of submit button, you can store the each value of input fields in a different varialble, for eg: var emailValue = document.getElementById('email_input_id').value; var passwordValue = document.getElementById('password_input_id').value; and after that you can call the click eventListner on that submit button and pass these values to the function which executes the node js function.

The thing that you are looking for is bodyparser:

npm i body-parser

First in your html files, make sure that your input have name attribute. Make sure to send a post request to a url when you click button (Just put the method="POST" in your form). Then require bodyparser in your serverfile and use it:

const BodyParser = require("body-parser")
app.use(BodyParser.urlencoded({extended:false})

Then in your route use body parser. The inputs are in req.body.<inputname>

app.post("url",(req,res)=>{
    req.body
}
Related