Node Mongo REST Service Post

2019-09-01 18:38发布

问题:

I have created a REST service using Node.js and MongoDB for using in one of my Android app. The get methods is working as expected when called from Android App. I am trying to build a JSON object from Android App with necessary details and post to the service.I am unable to post to my collections. Below is the code snippet I have used in my Node.js

app.post('/accounts/put/:uObject', function(req, res, next) {
  var username=uObject.name;

  db.collection('test').insert({"username":username},function(err,docs){if(err){
                res.send("There was some problem during insertions of linkes");
            }
           else{
                res.send("Fail");

           } });

});

What Am I doing wrong in this? I am getting the object as parameter and getting the values inside the function and passing to the insert.

回答1:

To get the parameter from the route you need to use req.params, in your case req.params.uObject. Also common practice in JavaScript is to return early upon a condition being met.

app.post('/accounts/put/:uObject', function(req, res, next) {
    var username = req.params.uObject;

    db.collection('test').insert({
        "username": username
    }, function(err, docs) {
        if (err) {
            return res.send("There was some problem during insertions of linkes");
        }
        res.send("Fail");
    });

});