Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

req.body returns an empty object eventhough data is passed through form

this is my index.js code and it returns an empty object even though data is passed on from the front-end

const express = require("express");
const cors = require("cors");
const app = express();

app.use(cors());
app.use(express.json());

app.post("/api/register", (req, res) => {
  console.log(req.body);
  res.json({ status: "ok" });
});

app.listen(8000, () => {
  console.log("listening on port 8000 . . . ");
});
like image 503
Rahul Kumar Avatar asked Dec 29 '25 13:12

Rahul Kumar


2 Answers

The main reason this does not work is some how the data passed in body is in text format while req.body is expecting json data make sure to double chek the 'Content-Type':'application/json' is set on the request headers

like image 71
Rahul Kumar Avatar answered Jan 01 '26 05:01

Rahul Kumar


For the specific case you're talking about, you usually need oa body parser to be able to access the form input fields. The minimum example that I advice you to build above it is the following:

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

Some other hints

Make sure that the request is being submitted with the header Content-Type: application/x-www-form-urlencoded or Content-Type: application/json Check if there any CORS problems Here's More reference for you

like image 42
nermineslimane Avatar answered Jan 01 '26 04:01

nermineslimane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!