【问题标题】:Node.js Express.js Mongoose Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clientNode.js Express.js Mongoose 错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
【发布时间】:2021-06-15 10:21:51
【问题描述】:

我有这个错误并尝试 evething,我读到“return”可能是错误的原因之一,promise 可能是另一个原因,但正如您在上面的代码中看到的那样,代码中没有任何遗漏。在 console.log(docs) 中,它会正确返回文档。 任何人都可以有一些解决方案,tks

exports.databaseController = (req, res) => {
   const promise = Database.find({}).exec()

   promise
    .then(docs => {
      if (!docs) {
      throw new Error('docs not found')
     }
     console.log(docs)
     return res.status(200).json(docs)
     })
    .catch(err => {
    console.log(err)                      // not found
    return res.status(404).json({ err })  // return your error msg
  })
}

// app
const controllerDatabase = 
require('../controllers/database.controller')

module.exports = app => {
  app.use((req, res, next) => {
  res.header('Access-Control-Allow-Headers', 'x-access-token, 
       Origin, Content-Type, Accept')
  next()
 })

  app.get('/api/v1/database', 
     controllerDatabase.databaseController)
}

// server.js
require('./app/routes/database.routes')(app)

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

    删除 console.log 。它会设置你为什么第二次调用你得到错误的标题

     console.log(res.json(docs)) // remove
    

    或者如果你需要console.log直接docs

     console.log(docs)
    

    【讨论】:

    • tks,但仍然无法正常工作,使用 console.log(docs) 我得到了文档,但在 Postmas 仍然没有回复
    • 请检查您的中间件app.use 功能。可能你有同样的控制台登录。更好地检查在线错误
    【解决方案2】:

    您已经在 console.log 中发送了您的回复。删除以下内容

    console.log(res.json(docs));
    

    这个错误就会消失。 如果您想控制台记录您的文档,请执行以下操作:

    console.log(docs);
    

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 2020-05-26
      • 2018-09-19
      • 2020-09-22
      • 2023-01-19
      • 2021-02-26
      • 2021-08-20
      • 2019-09-28
      相关资源
      最近更新 更多