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/jsonas 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.