[英]Node.js Express.js Mongoose Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I have this error and try evething, I read that 'return' can be one cause of the error and promise can be another one but as you can see in the code above none of this is missing in the code.我有这个错误并尝试 evething,我读到“返回”可能是导致错误的原因之一,promise 可能是另一个原因,但正如您在上面的代码中看到的那样,代码中没有任何一个缺失。 In the console.log(docs) it returns the document correctly.
在 console.log(docs) 中,它会正确返回文档。 can any one have some solution, tks
任何人都可以有一些解决方案,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)
Remove the console.log
.删除
console.log
。 its will set the header that why you are calling 2nd time you got the error它会设置 header 为什么你第二次调用你得到错误
console.log(res.json(docs)) // remove
Or if you need to console.log do with direct docs
或者,如果您需要 console.log 直接使用
docs
console.log(docs)
You are already sending your response in console.log.您已经在 console.log 中发送您的回复。 Remove the following
删除以下
console.log(res.json(docs));
and this error will go away.这个错误将 go 消失。 If you want to console log your docs do this:
如果您想控制台记录您的文档,请执行以下操作:
console.log(docs);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.