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:
body: JSON.stringify({"Data": "MY DATA"})
but get the same empty {}js POST Method. Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.
POST request using fetch API:To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we'll do a POST request on the same JSONPlaceholder and add a post in the posts. It'll then return the same post content with an ID.
JavaScript | fetch() Method. The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.
Add the following line in addition to your current bodyParser app.use() right before:
app.use(bodyParser.json());
This will enable bodyParser to parse content type of application/json
.
Hopefully that helps!
I feel a bit stupid now once I worked out what bodyParser.urlencoded
(source: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions)
Returns middleware that only parses urlencoded bodies
Solution
Changed the fetch()
request, from:
body: "MY DATA", headers: { "Content-Type": "application/json" }
to
body: JSON.stringify({"Data": "MY DATA"}), headers: { "Content-Type": "application/x-www-form-urlencoded" }
which solved the problem! Console logged:
{ '{"Data":"MY DATA"}': '' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With