'How to include all input value from HTML into req.body: Node.js (Express)

I am trying to get a value of checkbox, "1" in the following html, through req.body. However, in the req.body, username and password values are only included (passwordConfirm is not included as well).

How can I include the values of passwordConfirm and checkbox in req.body?Or is there another way to get the value of checkbox without req.body?

<form action="/register" method="POST">
        
        <label for="username">Username:</label>
        <input type="text" id="username" name="username"><br><br>
    
    
        <label for="password">Password:</label>
        <input type="password" id="password" name="password"><br><br>
    
    
        <label for="passwordConfirm">Confirm Password:</label>
        <input type="password" id="passwordConfirm" name="passwordConfirm"><br><br>
    
    
        <label>?</label>
        <input type="checkbox" id="checkbox" name="checkbox" value="1"><br><br>
    
        <button type="submit">Submit</button>

</form>

index.js

const controller = require("controller.js");
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.post("/register", controller.newUser);

controller.js

function newUser(req, res){
     console.log(req.body.checkbox);//returns undefined
}

module.exports =. {
     newUser
}

I tried putting <script> in html to include a function that returns the value of checkbox accessing document object and called the function in a server-side js file, but it did not work (server-side js cannot call the function in client-side js).



Solution 1:[1]

I tried the following server-side code, it works.

app.use(express.urlencoded({ extended: false }));
app.post("/register",  express.json(),(req, res) => {
   console.log(req.body);
});

Solution 2:[2]

const express = require('express');
const app = express();

/** Decode Form URL Encoded data */
app.use(express.urlencoded());

/** Show page with a form */
app.get('/', (req, res, next) => {
  res.send(`<form method="POST" action="/">
  <input type="text" name="username" placeholder="username">
  <input type="submit">
</form>`);
});

/** Process POST request */
app.post('/', function (req, res, next) {
  res.send(JSON.stringify(req.body));
});

/** Run the app */
app.listen(3000);

Solution 3:[3]

<form method="POST" action="/">
  <input type="text" name="username" placeholder="username">
  <input type="submit">
</form>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 The KNVB
Solution 2 Harsh2720
Solution 3 Harsh2720