Oge Obubu
Oge Obubu

Reputation: 69

Express.json() returns undefined

I am having trouble with express.json() function. I have checked numerous topics regarding this here and on the net but to no avail.

Here is the my code:

app.use(morgan("dev"));
app.use(cors());
app.use(helmet());
app.use(express.json());
app.use(express.urlencoded());
app.use("/api/users", userRoutes);
app.use("/api/articles", articleRoutes);

What I did:

  1. I ensured express.json() is above the router.
  2. Initially, express.urlencoded() wasn't there, due to my research I placed it there but yet nothing worked.
  3. I ensured I install the dependencies. They are available in the package.json file.

Here is my userController code:

exports.create = (req, res) => {
  try {
    const { name } = req.body;

    console.log(name);

    const user = {
      name,
    };

    res.json({
      message: user,
      text: "Is this working?",
    });
  } catch (error) {
    console.log(error);
  }

On Postman, here is what was returned:

{
    "message": {},
    "text": "Is this working?"
}

What should be the problem if express.json() passes the data to Postman but yet res.body returns undefined?

Upvotes: 0

Views: 1943

Answers (2)

Mudzia Hutama
Mudzia Hutama

Reputation: 502

How about change user to key value like :

exports.create = (req, res) => {
  try {
    const { name } = req.body;

    console.log(name);

    const user = {
      name: name // add this one
    };

    res.json({
      message: user,
      text: "Is this working?",
    });
  } catch (error) {
    console.log(error);
  }

Upvotes: 0

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

You need to add body-parser in your controler,

 npm install body-parser
const bodyParser = require('body-parser')
app.use(morgan("dev"));
app.use(cors());
app.use(helmet());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.use("/api/users", userRoutes);
app.use("/api/articles", articleRoutes);

You can follow the steps here :

Upvotes: 1

Related Questions