Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty request body

I generated two projects, one with create-react-app and the other with express generator.

I run the first one on localhost:3000 and the second one on localhost:3001.

I'am trying to send a POST request, but I receive an empty req.body.

Client side:

 handleSubmit(event) {
    event.preventDefault();
    var data = new FormData();
    for (const key of Object.keys(this.state)) {
      data.append(key, this.state[key]);
    }

    const url = "http://localhost:3000/course";
    fetch(url, {
      method: "POST",
      body: this.state
    })
      .then(response => response.text())
      .then(html => console.log(html));
  }

Server side:

app.js

app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});
app.use("/course", course);

router/course.js

router.post("/", function(req, res) {
  if (!req.body) {
    var course = new Course(req.body);
    course
      .save()
      .then(item => {
        res.json({ course: item });
      })
      .catch(err => {
        res.status(500).send("Unable to save to database");
      });
  }
  res.status(200).send("No data to save");
});
like image 529
Youssef Avatar asked Jan 03 '23 01:01

Youssef


1 Answers

body-parser needs Content-Type header to be set to 'Content-Type': 'application/json' in order to know that is has to parse the body

Try passing this to the headers

fetch('http://localhost:3000/course', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
});
like image 58
Stamos Avatar answered Jan 05 '23 14:01

Stamos