-1

I am trying to create a RESTful backend project made with Express and Mongoose but I am getting req.body empty when sending data from Postman tool.

My directory structure looks like this:

  • src
    • index.js
    • models
      • User.js
    • repositories
      • user.js
    • controllers
      • users.js
    • routes
      • users.js
      • index.js

User Repository

const User = require("../models/User");

class UserRepository {
  constructor(model) {
    this.model = model;
  }

  create(object) {
    return this.model.create(object);
  }
}

module.exports = new UserRepository(User);

User Controller

const UserRepository = require("../repositories/user");

function createUser(req, res) {
  const user = req.body; // empty

  UserRepository.create(user)
    .then(res.json)
    .catch(err => res.status(500).json(err));
}

module.exports = { createUser };

User Route

const express = require("express");
const UserController = require("../controllers/users");

const router = express.Router();

router.post("/", UserController.createUser);

module.exports = router;

This is the Sandbox project where I "demonstrate" what is going on.

Just in case you ask, I have set Content-Type: application/json as headers and send the data as raw (JSON), form-data (key / pairs), x-www-form-urlencoded (key pairs) on Postman but no look at all. I didn't try yet with a simple form... but I guess the mistake is over there.

halfer
  • 19,471
  • 17
  • 87
  • 173
Maramal
  • 2,577
  • 6
  • 36
  • 75
  • Can you try a new request in postman, and try with just raw (json) option? If not works can you add screenshots of the headers and body in the postman? – SuleymanSah Jan 11 '20 at 19:34
  • 1
    Maramal I tested your api, and saw req.body in the console. Just create a new post request, choose raw, and the JSON option. This will add `Content-Type:application/json` header automatically. – SuleymanSah Jan 11 '20 at 19:44
  • @SuleymanSah, indeed, it worked... – Maramal Jan 11 '20 at 20:28
  • @Dan, It helps, but I am not using body-parser but `express.json()`. – Maramal Jan 11 '20 at 20:29

1 Answers1

-1

Add this on top of index.js

var bodyParser = require('body-parser')
app.use(bodyParser.json())
Psartek
  • 409
  • 3
  • 9