Search code examples
htmlnode.jsformsnode-modulesform-data

Few field values are not showing up in the final output, i'm using nodejs


index.html

<form action="http://127.0.0.1:5555/sign" method="POST">
      <div class="main">
        <div class="name-container">
          <input type="text" class="input" placeholder="First Name" id="fname" />
          <input type="text" class="input" placeholder="Last Name" id="lname" />
        </div>
        <div class="gender_date">
          <div class="gen">
            <input type="radio" name="gender" value="male" id="male" />
            <label for="male">Male</label>
            <input type="radio" name="gender" value="female" id="female" />
            <label for="female">Female</label>
            <input type="radio" name="gender" value="other" id="other" />
            <label for="other">Other</label>
          </div>
          <div class="date-con">
            <input type="date" class="input" id='date' name="bday" />
          </div>
        </div>
      </div>
    </form>

the post request works properly but the names aren't showing up. back-end nodejs file => serve.js

const express = require("express");
const fs = require("fs");
const bodyParser = require("body-parser");
const app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.get("/sign", (req, res) => {
  res.send("Hello");
});
app.post("/sign", urlencodedParser, (req, res) => {
  res.send(req.body);
  let student = req.body;
  let students = [];
  students.push(student);
  let data = JSON.stringify(students, null, 2);

  fs.writeFile("./file.json", data, err => console.log("success"));
  console.log(students);
});

const PORT = 5555;
app.listen(PORT, err => {
  console.log(`Server Running at port: ${PORT}`);
});

file.json: Output

[
  {
    "gender": "male",
    "bday": "1999-07-05"
  }
]

The value from "First Name" and "Last Name" fields aren't showing up in the final output. No matter what I change I couldn't get it to work properly. Thank you in advance.


Solution

  • Try it

    <form action="http://127.0.0.1:5555/sign" method="POST">
      <div class="main">
        <div class="name-container">
          <input type="text" class="input" placeholder="First Name" name="fname" />
          <input type="text" class="input" placeholder="Last Name" name="lname" />
        </div>
        <div class="gender_date">
          <div class="gen">
            <input type="radio" name="gender" value="male" id="male" />
            <label for="male">Male</label>
            <input type="radio" name="gender" value="female" id="female" />
            <label for="female">Female</label>
            <input type="radio" name="gender" value="other" id="other" />
            <label for="other">Other</label>
          </div>
          <div class="date-con">
            <input type="date" class="input" id='date' name="bday" />
          </div>
        </div>
      </div>
    </form>