1

my client-side code:

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="form.css" />
  </head>
  <body>
    <form action="/login" method="post" class="form">
      <input type="text" name="txt" class="txt" id="txt" placeholder="name" />
      <input type="submit" class="submit" id="submit" />
    </form>
    <script defer src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
      let submit = document.querySelector(".submit");
      const form = document.querySelector(".form");

      form.addEventListener("submit", (e) => {
        e.preventDefault();

        const formData = new FormData(form);

        const formObject = {};
        formData.forEach((value, key) => {
          formObject[key] = value;
        });

        console.log(axios.defaults)

        axios
          .post("http://localhost:8080/login", formObject)
          .then(function (response) {
            console.log(response.data);
          })
          .catch(function (error) {
            console.log(error);
          });
      });
    </script>
  </body>
</html>

my server side code :


const app = express();
const path = require("path");

app.use(express.static('./public',{index:'form.html'}));

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

    app.post('/login',(req,res)=>{
    //const txt = req.body;
      console.log('logged data: ',req.body);
      res.send('Thanks');
    })
app.listen(8080, () => {
  console.log('server is running...in port 8080')

 });

First of all please keep in mind that I am new to the backend. when I try to console.log the logged data it's returning me an empty object I can't understand why my req.body is returning an empty object but when I try to do the same by giving action:"/login" and method: "post" inside the form tag it works as expected and gives me the input I provide. Please someone help me my head is burning and thankyou in advance.

Rahan Ajai
  • 87
  • 7

1 Answers1

1

req.body is empty because when you send it with axios, you're actually sending a JSON (application/json) payload, and you don't have a JSON payload parser on backend, only URL-encoded, while the HTML form sends it in the application/x-www-form-urlencoded format, which is why it works.

So, you need to send URL-encoded request with axios, you can use URLSearchParams to convert JSON object to query string. Try this.

axios
  .post("http://localhost:8080/login", new URLSearchParams(formObject))

Or, simply add a JSON parser to the backend, and your original JSON request will work, use built in parser:

app.use(express.json());
traynor
  • 5,490
  • 3
  • 13
  • 23
  • bro its working as you said but bro why the res.send('thanks') is not showing up – Rahan Ajai May 21 '23 at 17:03
  • 1
    what do you mean it's not showing, it should show in dev tools, if you mean it's not showing on the web page, then you need to add it, for example, add div element, and then add response.data to it, see: [How to append text to a div element?](https://stackoverflow.com/a/34551817/4321299) – traynor May 21 '23 at 19:24