-1

I have a simple express app that gets one fetch request, the fetch looks like this:

let opts = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  mode: "no-cors",
  body: {
    "test": "test"
  }
}

fetch("http://localhost:3001/data", opts)

and it's in the setup() function.

the serverside code looks like this:

const express = require('express');
const app = express();
app.listen(3001, () => console.log("listening at 3001"));
app.use(express.static("public"));
app.use(express.json());

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

in my console what I get after refreshing everything is this:

listening at 3001
post recived
{}

the body of the post is not undefined but it is empty, I cannot figure out what the problem is for the life of me

Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
Alon Raz
  • 1
  • 1
  • runnable snippets are for snippets that can be executed inside browsers. please format your code by wrapping it with tripple ticks (```) next time – Tibebes. M Jan 08 '21 at 12:50
  • You need to make the body a string as well as set the right headers, see https://stackoverflow.com/q/29775797/3001761 – jonrsharpe Jan 08 '21 at 12:53

1 Answers1

0

Problem one: no-cors

mode: "no-cors", is a declaration that you are not going to do anything which requires permission from CORS and that any CORS related errors should be suppressed.

You need permission from CORS in order to set an application/json content-type header.

So the first job is to remove that line.


Problem two: CORS

Then you need to change the server so it grants you permission to make the request.

Install the cors middleware package and follow the setup instructions there.

Make sure you enable support for preflight requests because setting an application/json content-type header requires a preflight.


Problem three: JSON

You claim you are sending JSON, but you are passing fetch a plain object.

When you do that, fetch will convert it to a string using the built-in toString method. This gives you "[object Object]" which is not JSON and doesn't contain your data.

You need to pass JSON instead.

body: JSON.stringify({
   "test": "test"
})
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335