node.js - 出现错误 : Can't set headers after they are sent

标签 node.js mongodb rest mongoose

我正在尝试在 Node、mongoose 中实现搜索功能。
我喜欢搜索两个参数,要么按姓名,要么按艺术家。如果两者中的任何一个与当前数据库匹配,它应该返回值(使其安静)

但是,它正在发送响应错误:发送后无法设置 header 。
未处理的 promise 拒绝已被弃用,甚至我得到的响应是空的

我正在尝试在其中执行两个查询,我认为这可能是问题所在。我应该如何编写它,或者编写这些类型的功能的正确方法是什么

这是我当前的代码

app.get('/search/:textValue',controller.findData)

和 findData

exports.findData = (req, res)=>{

    const searchParam = req.params.textValue;
    let storeResult = []
    if(searchParam==null|| searchParam == undefined || searchParam==""){
        return res.status(500).json("Send a valid input")
     }
  else{
        Song.find({artists: new RegExp(searchParam, "i")}).lean().then((data)=>{
            storeResult[0].push(data)
        }).catch((err)=>{
            return res.send(err)
        })

        Song.find({name: new RegExp(searchParam, "i")}).lean().then((data)=>{
            storeResult[1].push(data)
        }).catch((err)=>{
            return res.send(err)
        })

        return res.send(storeResult)
    }
}

它们对于单个查询的工作非常好,这里应该进行哪些更改?

最佳答案

您的方式是在填写storeResult之前使用res.send(storeResult)。为何如此?您用尚未调用的 .then() 回调填充它。

尝试链接您的 then 回调。

 Song.find({artists: new RegExp(searchParam, "i")}).lean()
.then((data)=>{
    storeResult.push(data);
})
.then(() => {
    Song.find({name: new RegExp(searchParam, "i")}).lean()
    .then((data)=>{

        storeResult.push(data)
    })
    .then(() => {
        console.log(storeResult)
        res.send(storeResult)
    })  
})
.catch((err)=>{
    console.log("Here is error")
    console.log(err)
    res.send(err)
})
}

提示。在调试器中单步执行对于排除此类代码的故障非常有用。

关于node.js - 出现错误 : Can't set headers after they are sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54840898/

相关文章:

javascript - 解析 DynamoDB 请求

node.js - Node js - Express js代码在重定向后执行

javascript - 我无法在 Sails.js 上建立简单的关联(关系模型的字段显示未定义)

python - pymongo update_one(), upsert=True 不使用 $ 运算符

mongodb - 无法使用 salat : command failed [listDatabases] 从 Play 应用程序连接到 MongoDB

jQuery - 发送跨域 PUT/DELETE 请求

python - Flask RESTful 销毁用户 token

mysql - 在 Node.js 中使用 mysql 和 Promise

json - 如何在Grails中使用REST API发送JSON有效负载?

javascript - 在 Node.js 中使用 readline