0

Can not read data from express form ( return null), I used the body parser in the server.js

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

Here's the router method

router.post('/', async (req, res) => {
    console.log('customer');
    const { error } = validate(req.body);
    console.log(req.body); 
    if (error) return res.status(400).send(error.details[0].message);

    let customer = new Customer({
        name: req.body.name,
        mobile: req.body.mobile,
        isGold: req.body.isGold
    })
    console.log(customer);
    customer = await customer.save();

    res.send(customer);
});

Here's the html form , I have 3 fields ( name , mobile , isGold) :-

 <form action="/api/customer" method="POST">
    <div class="form-row">
      <div class="form-group col-md-6">
        <label for="name">Full Name</label>
        <input type="name" class="form-control" id="name" placeholder="name">
      </div>   
    </div>
    <div class="form-row">

      <div class="form-group col-md-6">
        <label for="mobile">Mobile</label>
        <input type="mobile" class="form-control" 
        id="mobile" placeholder="Enter your Mobile">
      </div>
    </div>
 
    <div class="form-group">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" id="isGold">
        <label class="form-check-label" for="gridCheck">
          Is Gold
        </label>
      </div>
    </div>
     <button type="submit" class="btn btn-primary">Save</button>
  </form>
  • You do not need `body-parser`, the library in the newer versions of Express. replace with `express.json()` and `express.urlencoded({ });` – cross19xx Feb 21 '19 at 14:05
  • Okay , But I got null before using the body parser. – Ahmed Rabie Feb 21 '19 at 14:07
  • You can also experiment by removing the `extended: true` flag. if this does not work, I have a feeling there is more to the code – cross19xx Feb 21 '19 at 14:10
  • I see that you don't binding data value to the http body, Can you try it? https://stackoverflow.com/a/21284362/5589964 – Chuong Tran Feb 21 '19 at 14:19

1 Answers1

0

You need to add name property to the input field.

<div class="form-group col-md-6">
        <label for="mobile">Mobile</label>
        <input type="mobile" class="form-control" 
        id="mobile" name="mobile" placeholder="Enter your Mobile">
      </div>
</div>

Usually GET/POST request is sent in form of key:value pair.Here key is the name attribute of the form.

example : http://example.com/page?parameter=value&also=another

Here "parameter"(& "also") is a form input field name.

Mahendra suthar
  • 401
  • 5
  • 18