简体   繁体   中英

Function is getting undefined parameter Node.js

I'm working with an application that uses Mongo as DB and node.js. I created a function which is meant to recieve a parameter named orderedBy but my console.log, prints an undefined parameter. Why is this happening? Here's the code.

exports.showAll = function(orderedBy, callback){

var query = {orderedBy: orderedBy}
console.log("Orderer by ===== "+ orderedBy);

var array = models.Orden.find(query).lean().exec(function(err, orders) {
    if( orders.length > 0) {
        callback({'array' : orders});
        //callback({'array' : JSON.stringify(orders)});
    }
    else {
        callback({'error' : "You don't have any orders"});
    }
});}

And here i call showAll

app.post('/api/showAll', function(req, res) {
      var orderedBy = req.body.orderedBy;
      ordenes.showAll(orderedBy, function(found){
           console.log(found);
           res.json(found);
      });
 });

Basically, what I want is get an ID and show how many orders that person has. But my response is always "You don't have any orders" mainly because me console log, shows that orderedBy is undefined.

And yes i'm making sure i'm sending the correct ID, simulating it with Postman

your req request object have two properties called

  • body: when you send a POST/PUT request will be populate by the body of the request
  • query: when you send a request, (no matters the method) will be populate by the queryString. example http://localhost:3000?orderBy=AAAA

    on your server side you can can req.orderBy === 'AAAA'

Thought it was my function being wrong, but it was my parameters. I was stupidly sending form-data, instead of x-www-form-urlencoded in postman. It was never broken, thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM