fetch() POST request to Express.js generates empty body {}
Asked Answered
T

2

31

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:

  1. I also tried sending body in fetch() as body: JSON.stringify({"Data": "MY DATA"}) but get the same empty {}
  2. I either my fetch() request, or my bodyParser(), is not setup correctly.
Theisen answered 7/10, 2018 at 0:7 Comment(0)
F
30

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!

Faradic answered 7/10, 2018 at 0:21 Comment(4)
Ahhhh! I had this before, but after app.use(bodyParser.json()). Switching these around solved it! Thank you.Theisen
The language around 'before' and 'after' here - is a bit confusing! Any clarity on that would be helpful.Ferraro
He means to add app.use(bodyParser.json()); right before the app.post(...)Taliped
The 2021 version is to use app.use(express.json())Quilting
T
9

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"}': '' }

Theisen answered 7/10, 2018 at 0:21 Comment(2)
You can keep the application/json content type, just need to add another line of configuration. Try my answer with you original fetch and content type.Faradic
@AlexanderStaroselsky, yes, I prefer your answer since it produces a cleaner response: { data: 'MY DATA' }Theisen

© 2022 - 2024 — McMap. All rights reserved.