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

Time:01-20

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 . . . ");
});

CodePudding user response:

if you are using multipart/form-data or require a file upload from frontend you will need a multer as middleware for your post/patch requests, otherwise you can set your frontend to send application/json

[edit] this line looks missing from your index.js

app.use(express.urlencoded({extended: true}))

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related