简体   繁体   English

函数正在获取未定义的参数Node.js

[英]Function is getting undefined parameter Node.js

I'm working with an application that uses Mongo as DB and node.js. 我正在使用将Mongo用作DB和node.js的应用程序。 I created a function which is meant to recieve a parameter named orderedBy but my console.log, prints an undefined parameter. 我创建了一个函数,该函数旨在接收名为orderedBy的参数,但我的console.log打印了未定义的参数。 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 这里我叫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. 基本上,我想要的是获取一个ID并显示该人有多少订单。 But my response is always "You don't have any orders" mainly because me console log, shows that orderedBy is undefined. 但是我的回答总是“您没有任何订单”,主要是因为我的控制台日志显示,orderedBy是未定义的。

And yes i'm making sure i'm sending the correct ID, simulating it with Postman 是的,我确保我发送的是正确的ID,并用Postman模拟

your req request object have two properties called 您的req请求对象都要求两个属性

  • body: when you send a POST/PUT request will be populate by the body of the request 正文:当您发送POST / PUT请求时,请求的正文将被填充
  • query: when you send a request, (no matters the method) will be populate by the queryString. 查询:当您发送请求时(无论方法如何)都将由queryString填充。 example http://localhost:3000?orderBy=AAAA 例如http:// localhost:3000?orderBy = AAAA

    on your server side you can can req.orderBy === 'AAAA' 在您的服务器端,您可以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. 我愚蠢地发送了表单数据,而不是用邮递员发送x-www-form-urlencoded。 It was never broken, thanks. 从来没有坏过,谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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