Unable to send data from axios to node server returning empty object
P粉141911244
P粉141911244 2024-03-31 11:14:22
0
1
2501

My client 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 backend. When I try to console.log the logged data, it returns an empty object, I can't understand why my req.body returns an empty object, but when I try to do the same by giving action:"/login" and the method When: "post" inside the form tag it works as expected and gives me the input I provide. Please someone help me, my head is burning, thank you in advance.

P粉141911244
P粉141911244

reply all(1)
P粉333186285

req.body is empty because when you send it using axios you are actually sending a JSON (application/json) payload , and the backend doesn't have a JSON payload parser, only URL encoding, and the HTML form sends it in application/x-www-form-urlencoded format, that's why it works.

Therefore, you need to use axios to send URL-encoded requests, which you can do by using URLSearchParams to convert the JSON object into a query string. Try this.

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

Alternatively, just add a JSON parser to the backend and your raw JSON requests will work, using the built-in parser:

app.use(express.json());
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!