【问题标题】:Getting error - Can't set headers after they are sent出现错误 - 发送后无法设置标题
【发布时间】:2017-05-31 06:27:24
【问题描述】:

我正在尝试使用猫鼬查询对我的页面进行分页。但是收到错误后无法设置标头。如果不使用分页,排序工作正常。

我的错误在哪里。这个错误是什么意思?下面是我的代码

app.js

var options = {
    perPage:3,
    delta : 1,
    page:5

};
app.get("/api/Productlist",function(req,res){
    var query = ProductModel.find(function(err,items,count){
        if(err){
            var empty = {}
            res.send(JSON.stringify(empty));
            console.log("cannot finf data");
        }else{
        res.send(JSON.stringify(items));
                }           
 }).sort({"name":1})
    .paginate(options,function(err,items){
        if(err){
            console.log("Cant paginate");
        }
        console.log(items);
    });

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    一些事情:

    1) 你可以写 res.json 而不是 res.send(JSON.stringify(object));

    2) 在您的数据库查询中,您会在分页完成之前立即调用该函数并发送响应。我发现如果你不打算让你的应用程序变得非常大,你可以使用跳过和限制,这是一个例子,希望对你有帮助。

    yourModel.find().sort({name:1}).skip(0).limit(3).then(data=>{
      if(data.length === 0){
        let err = new Error();
        err.message = "cannot find data";
        err.status = 404;
        res.status(err.status).json(err);
      }
      res.json(data);
    });
    

    3)如果你想保持当前结构,这里是一个例子,你只需要调用你的函数一次,像这样,不需要找到然后再次分页

    ProductModel.find().sort({name:1}).paginate(yourOptions,function(err,items){
       console.log(items)
    })
    

    【讨论】:

    • 感谢您的回复。我使用了您的选项 3。但它显示错误 ProductModel.find().sort({name:1}).paginate... is not a function.here is my code app.get("/api/Productlist", function(req,res){ ProductModel.find().sort({name:1}).paginate(options,function(err,items){ if(err){ console.log("找不到数据"); } else{ res.send(JSON.stringify(items)); } }); });
    【解决方案2】:

    此代码工作正常,一次只查询 2 条记录。但我想在我的 html 页面上显示带有页码的记录。如何将 html 正文与此查询绑定。

    ProductModel.find().paginate(2,2).
            exec(function(error,item){
                if(error){
                    console.log("Error");
                }else{
    
                    console.log(item);
                    res.send(JSON.stringify(item));
                }
        });
    

    【讨论】:

      猜你喜欢
      • 2019-07-17
      • 2015-11-13
      • 2015-03-07
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      相关资源
      最近更新 更多