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

Time:03-25

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

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.post("/register", (req, res) =\> {
console.log(req.body.checkbox); //returns undefined
});

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).

CodePudding user response:

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);
});

CodePudding user response:

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);

CodePudding user response:

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