2

i'm created an api and for this i'm using node.js. what is happening is following it whenever i make a post request even after passing the data correctly i am getting a validation error saying that the fields are empty. I did a check I noticed that req.body is undefined even installed and imported the body-parser I´m using body-parser: 1.19.0

I already installed the body-parser and use. enter image description here

//Index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const bodyParser = require("body-parser");
//Import Router
const authRoute = require("./routes/auth");

dotenv.config();

//Import Router Middlewares
app.use("/api/user/", authRoute);

//MiddleWare
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


mongoose
  .connect(process.env.DB_MONGO, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
  })
  .then(() => {
    console.log("DB is connect");
  })
  .catch((err) => {
    console.log(err);
  });

app.listen(8081, () =>
  console.log("Servier is running  http://localhost:8081")
);


This is the auth.js

const router = require("express").Router();
const User = require("../model/User");

//post method
router.post("/register", async (req, res) => {
  const user = new User(req.body);
  console.log(req.body);
  user.save((err, data) => {
    if (err) {
      console.log(err);
      res.status(400).json({
        message: err,
      });
    } else {
      res.json({
        message: data,
        status: true,
      });
    }
  });
});

  • https://stackoverflow.com/questions/24543847/req-body-empty-on-posts – Tushar Gupta - curioustushar Mar 21 '21 at 01:31
  • Do not use both `app.use(express.json());` and `app.use(bodyParser.json());` Pick one or the other, preferably the `express` version and there is no need for the separate `body-parser` module any more as Express has that functionality built-in now. – jfriend00 Mar 21 '21 at 02:12

3 Answers3

3

You need to fix the ordering of your middleware relative to the routes that depend upon it.

Change this:

//Import Router Middlewares
app.use("/api/user/", authRoute);

//MiddleWare
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

to this:

//MiddleWare
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//Import Router Middlewares
app.use("/api/user/", authRoute);

And, remove this:

const bodyParser = require("body-parser");

The order matters here. Your middleware must be BEFORE the routes that need it.

Also, note that the separate body-parser module is no longer necessary as Express already includes the body-parser module internally and you can get access to it via express.json() and express.urlencdoed() and others.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

add this line bro:

app.use(express.urlencoded({ extended: false }))
bahoz99
  • 121
  • 1
  • 6
  • The OP already has `app.use(bodyParser.urlencoded({ extended: false }));` which delivers similar functionality. – jfriend00 Mar 21 '21 at 02:13
  • I using it for receive req.body succesfully – bahoz99 Mar 21 '21 at 02:15
  • Yes, but that is not the issue here as the OP already has middleware installed for reading the body. See my answer here for a description of the issue. – jfriend00 Mar 21 '21 at 02:17
0
  • If routing takes place in app , then use :

       app.use(express.json)
    
  • If routing takes place in router folder , then use :

       router.use(express.json)
    

It'll by default uncover the req.body into json format.

(For which installing and initializing express is a must)

Though body.parser and express.json help encoding req.parser but using both is not an optimal solution.Plus you've already middleware installed . Hence, try going by simpler method of express.

remote007
  • 41
  • 2