Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Express POST request body outputting unidentified and {}

I am difficulty retrieving the body of an express post request form a HTML form. In my code I attempt to extract it normally raw and with JSON.stringify. Still no dice, just outputs:""Body: "undefined" received in app.js! ——- Body: "[object Object]" received in app.js!"" and the console outputs undefined and {}. Any help is appreciated. Bellow is both my JS code and HTML code.

const express = require('express');
const app = express();

const path = require('path');

const bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 

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

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, './index.html'));
})

app.post('/submit-form', function(req, res) {

    var x = req.body.key;
    var y = req.body;

    console.log(x);
    console.log(y);

    console.log(JSON.stringify(x));
    console.log(JSON.stringify(y));
    
    res.send(`Body: "${x}" recieved in app.js! ------- Body: "${y}" recieved in app.js!`);

})

app.listen(4001, function() {
    console.log("Server is listening on port 4001...");
})
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sample Site</title>

  <style>
    body { padding-top: 50px; }
  </style>
</head>
<body>

  <div class="container">
    <div class="jumbotron">
      <h1>res.sendFile() Works!</h1>
      
      <form method="POST" action="/submit-form", body= "key: 'hellow wolrd'"}>
        <input type="submit">
      </form>

    </div>
  </div>

</body>
</html>```

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The body of a POST request is determined by the values of the named form controls (input, select, etc elements) in the form.

There is no body attribute for the <form> element.

MDN has a forms + express tutorial that I recommend you read.

 <form method="POST" action="/submit-form">
     <input name=key value="hello, world">
     <button>Submit</button>
 </form>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading