I have just started learning node.js (Express) and I created a simple application that communicate with a very simple mongo database. I have a collection called 'Users' in a database called 'testDB'. I created my skeleton in my node.js application and I followed 'separation of concern' logic.
In my controller folder I have a subfolder called usersController. Inside that subfolder, there is 2 .js files, one is usersControllers.js and the other is usersRoutes.js
Inside usersRoutes.js there is the following code:
"use strict";
var express = require('express');
var router = express.Router();
// require the controller here
var usersController = require("./usersController.js")();
router
.get('/', usersController.getAllUsers)
.post('/', usersController.createUser);
module.exports = router;
As you can see, I am calling a function (factory) that is inside usersController.js called 'createUser'. This function is written like the following:
"use strict";
var MongoClient = require('mongodb').MongoClient;
var usersController = function(){
var getAllUsers = function(req, res){
MongoClient.connect('mongodb://localhost/testDB', function(err, db){
if(err){
throw err;
}
db.collection('Users').find().toArray(function(err, doc){
if(err){
throw err;
}
else{
return res.status(200).json(doc);
db.close();
}
});
});
};
var createUser = function (req, res) {
MongoClient.connect('mongodb://localhost/testDB', function(err, db){
console.log(req.body);
db.close();
});
};
return {
getAllUsers: getAllUsers,
createUser: createUser
};
};
module.exports = usersController;
I have created a post man request to explore how to extract the body data that I am sending. The request is like the following
In the header I have 2 keys
- Accept: application/json;charset=UTF-8
- Content-Type: application/json
In the body I have the following raw text:
{
"Users": {
"First Name": "Ahmed",
"Last Name": "Rahim",
"Username": "rahima1",
"Passwoed": "secure"
}
}
Based on the previous scenario, I have a few questions:
- How to extract the body from the request. I tried to dig into 'req' but I couldn't find what I am looking for?
- passing a plain password like that is not good, right? Any suggestions to pass an encrypted password (maybe sha)?
- Is there something wrong in the request itself?
Any side note will help me a lot from experts like you guys :)
Thank you all!!
req.body
it's required. – adeneo