-1

As the title states req.body is printing out an empty object or {}. I have looked at a few other posts and can see this is a common problem but none of the posted solutions that I have found have fixed the problem.

client side code

 const myData = "hello world";
  const options = {
    method: "POST",
    header: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(myData),
  };
  fetch("http://localhost:8000/api", options);

server side node.js code

app.use(express.json({ limit: "1000mb" }));
app.use(express.urlencoded({ limit: "1000mb", extended: true }));

app.listen(8000, function () {
  console.log("server is running");
});

app.use(express.static("public"));

app.post("/api", (req, res) => {
  console.log(req.body);
});

edit: I believe body-parser has been a part of express for a while now and express implements its own version of body parser through

app.use(express.json({ limit: "1000mb" }));
app.use(express.urlencoded({ limit: "1000mb", extended: true }));
codes
  • 21
  • 4

1 Answers1

0

You have two problems.

Headers

Your immediate problem is that you made a typo. The option name you need to pass to fetch is headers (plural) not header.

Since you failed to say you were sending JSON, you bypassed the JSON parsing middleware entirely.

Modern JSON

The current JSON specification allows a JSON text to consist of any JSON data type.

The original specification only allowed the top level to be an object or an array.

The middleware you are using enforces the original specification by default, so trying to send a string as your entire JSON text will throw an exception.

To allow strings set strict:

app.use(express.json({ limit: "1000mb", strict: false }));
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335