Goal: send some defined string data from HTML in a fetch()
function e.g. "MY DATA"
My code:
HTML
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function fetcher() {
fetch('/compute',
{
method: "POST",
body: "MY DATA",
headers: {
"Content-Type": "application/json"
}
}
)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
</script>
</body>
</html>
Server.js
var express = require("express");
var app = express();
var compute = require("./compute");
var bodyParser = require("body-parser");
//not sure what "extended: false" is for
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/compute', (req, res, next) => {
console.log(req.body);
var result = compute.myfunction(req.body);
res.status(200).json(result);
});
Currently: console.log(req.body)
logs {}
Desired: console.log(req.body)
logs "MY DATA"
NOTES:
- I also tried sending body in fetch() as
body: JSON.stringify({"Data": "MY DATA"})
but get the same empty {} - I either my fetch() request, or my bodyParser(), is not setup correctly.
app.use(bodyParser.json())
. Switching these around solved it! Thank you. – Theisen