1

I am Trying to insert data into Database using post request as follows

127.0.0.1:3000/api/users?fname=asd&lname=edc&emailid=asdas.asds@gmail.com&userpass=dasd

but in database blank data is entered. I am using MongoDB for database.

I am doing this using AJAX request following is the code I am Using

addUser(dataUser){
 console.log("Adding user:", dataUser);
 $.ajax({
   type: 'POST', url: '/api/users', contentType: 'application/json',
   data: JSON.stringify(dataUser),
   success: function(data) {
     console.log("check it");
   }.bind(this),
   error: function(xhr, status, err) {
     // ideally, show error to user.
     console.log("Error adding bug:", err);
   }
 });
}

this is mt POST method in nodeJS file

app.post('/api/users', function(req,res){
 console.log("Req body:", req.body);
 var newUser = req.body;
 db.collection("Users").insertOne(newUser, function(err, result) {
   var newId = result.insertedId;
   db.collection("Users").find({_id: newId}).next(function(err, doc) {
     res.json(doc);
   });
 });
});

I checked that dataUser variable giving correct values after converting into JSON but still at nodeJS code I am getting Blank JSON Data

AviatorX
  • 492
  • 1
  • 7
  • 17

2 Answers2

0

For getting body from req with express you will need body-parser module using npm install body-parser as body-parser module has been removed from recent release of express.

After adding this dependancy you need to add these lines in you nodejs file.

var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({
   extended: true
}));

app.use(bodyParser.json());

Refer

Let me know if it helps.

Community
  • 1
  • 1
Samarth
  • 773
  • 1
  • 6
  • 14
0
app.post('/api/users', function(req,res){
 console.log("Req body:", req.body);

 //parse json string
 var newUser = JSON.parse(req.body);

 db.collection("Users").insertOne(newUser, function(err, result) {
   var newId = result.insertedId;
   db.collection("Users").find({_id: newId}).next(function(err, doc) {
     res.json(doc);
   });
 });
});
Love-Kesh
  • 777
  • 7
  • 17