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 >
<div >
<h1>res.sendFile() Works!</h1>
<form method="POST" action="/submit-form", body= "key: 'hellow wolrd'"}>
<input type="submit">
</form>
</div>
</div>
</body>
</html>```
CodePudding user response:
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>