Purpose: Implement a function in fetch()
to send specified string data from the HTML document, for example "MY DATA"
Here is the code snippet:
HTML Code:
<!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 File:
var express = require("express");
var app = express();
var compute = require("./compute");
var bodyParser = require("body-parser");
// The purpose of "extended: false" is uncertain
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);
});
Current Output: console.log(req.body)
displays {}
Expected Output: console.log(req.body)
should show "MY DATA"
Important Points:
- I attempted sending the body in the fetch() function as
but received an empty {}.body: JSON.stringify({"Data": "MY DATA"})
- I suspect that either my fetch() request or my bodyParser() configuration is incorrect.