I'm doing mongodb database after tutorial from NetNinja. Since I'm kinda bad with js, I'm just following his actions. I'm stuck with:
在NetNinja的教程之后,我正在做mongodb数据库。因为我对js有点不好,所以我只是关注他的行为。我被困在:
node:internal/errors:496
ErrorCaptureStackTrace(err);
^
...
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I'm having only 2 files:
app.js
我只有两个文件:app.js
const express = require('express')
const { connectToDb, getDb} = require('./db')
const app = express()
let db
connectToDb((err) => {
if(!err) {
app.listen(3000, () => {
console.log('app listening on port 3000')
})
db = getDb()
}
})
app.get('/books/books', (req, res) => {
let books = []
db.collection('books')
.find()
.sort({ author: 1 })
.forEach(book => books.push(book))
.then(() => {
res.status(200).json(books)
})
.catch(() => {
res.status(500).json({error : 'Could not fetch the documents'})
})
res.json({mssg: "welcome to the api"})
})
db.js
db.js
const { MongoClient } = require('mongodb')
let dbConnection
module.exports = {
connectToDb: (cb) => {
MongoClient.connect('mongodb://0.0.0.0:27017/bookstore')
.then((client) => {
dbConnection = client.db()
return cb()
})
.catch(err => {
console.log(err)
return cb(err)
})
},
getDb: () => dbConnection
}
I found the place that throws me this error, when I'm removing it, there's no error:
app.js, app.get block
我找到了引发这个错误的地方,当我删除它时,没有错误:app.js,app.get块
.then(() => {
res.status(200).json(books)
})
Since NetNinja has no problems, error could be triggered by different versions of Node, but I dunno for sure.
Is there a replacement to '.then', that'll let me use database?
由于NetNinja没有问题,不同版本的Node可能会触发错误,但我不确定。有没有替代“.then”的方法,可以让我使用数据库?
更多回答
优秀答案推荐
The error in the code you provided is that you're sending a response (res.json({mssg: "welcome to the api"})) after making a database query. In Node.js and Express, the response should only be sent once. When you send a response, you can't send another one.
您提供的代码中的错误是,您在进行数据库查询后发送了一个响应(res.json({mssg:“欢迎使用api”})。在Node.js和Express中,响应应该只发送一次。发送响应时,无法再发送另一个响应。
This error does not occur because of the node version or .then
its occuing because you are sending a response 2 time
此错误不是因为节点版本而发生的,或者。然后是因为您发送了2次响应而引起的
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
First:
第一:
res.json({mssg: "welcome to the api"});
Second:
第二:
res.status(200).json(books);
Fix:
修复:
just remove the second response
只需删除第二个响应
app.get('/books/books', (req, res) => {
let books = []
db.collection('books')
.find()
.sort({ author: 1 })
.forEach(book => books.push(book))
.then(() => {
res.status(200).json(books)
})
.catch(() => {
res.status(500).json({error : 'Could not fetch the documents'})
})
})
更多回答
that worked, thank you
起作用了,谢谢
Kindly mark this answer as the correct one. Thanks!
请把这个答案标记为正确答案。谢谢
我是一名优秀的程序员,十分优秀!