我是node.js的新手,正在学习教程,但是当我刷新localhost:3000/books时,代码返回错误
错误:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
产品代码:app.js
const express = require('express');
const { connectToDb, getDb } = require('./db');
console.log('starting');
// init app & middleware
const app = express();
console.log('init complete');
// db connection
let db;
connectToDb((err) => {
console.log('connecting to db');
if (!err) {
app.listen(3000, () => {
console.log('app listening on port 3000');
});
db = getDb();
} else {
console.log(err);
}
});
//routes
app.get('/books', (req, res) => {
let books = [];
db.collection('books')
.find() // cursor toArray forEach
.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:
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
};
我用compass托管mongodb服务器:我有一个以bookstore命名的数据库和一个以books命名的集合在我拥有的书籍中:
[{
"_id": {
"$oid": "636faa18a918cf889958ea12"
},
"title": "Name of wind",
"author": {
"firstName": "Patrick",
"lastName": "Rothfuss"
},
"pages": 500,
"genres": [
"fantassy",
"magical"
],
"rating": 9,
"reviews": [
{
"name": "Ludwig",
"body": "AWESOME!"
}
]
},{
"_id": {
"$oid": "636facd8a918cf889958ea16"
},
"title": "Book of fire?",
"author": {
"firstName": "Willem",
"lastName": "Johnson"
},
"pages": 350,
"genres": [
"fantassy",
"comedy"
],
"rating": 6,
"reviews": [
{
"name": "Ludwig",
"body": "BAD!"
}
]
},{
"_id": {
"$oid": "636facd8a918cf889958ea17"
},
"title": "Thrones of destiny",
"author": {
"firstName": "Jonas",
"lastName": "Adams"
},
"pages": 689,
"genres": [
"magical",
"fantassy"
],
"rating": 10,
"reviews": [
{
"name": "Ludwig",
"body": "The best!"
}
]
},{
"_id": {
"$oid": "636facd8a918cf889958ea18"
},
"title": "Idiots!",
"author": {
"firstName": "Jack",
"lastName": "Phiers"
},
"pages": 486,
"genres": [
"action",
"comedy"
],
"rating": 8,
"reviews": [
{
"name": "Ludwig",
"body": "Great!"
}
]
},{
"_id": {
"$oid": "636facd8a918cf889958ea19"
},
"title": "Where are we?",
"author": {
"firstName": "Jone",
"lastName": "Johnson"
},
"pages": 685,
"genres": [
"magical",
"sci-fi"
],
"rating": 7.6,
"reviews": [
{
"name": "Ludwig",
"body": "Good!"
}
]
},{
"_id": {
"$oid": "63737fae2ea0cb2ca699eec7"
},
"title": "Colour Magic",
"author": {
"firstName": "Terry",
"lastName": "Pretchett"
},
"pages": 768,
"rating": 7,
"genres": [
"fantassy",
"comedy"
]
}]
型
当注销我在app.js中创建的books数组时,它是一个空数组
1条答案
按热度按时间eqqqjvef1#
问题不在于数据库。
由于错误显示
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
,响应被发送到客户端两次。两次是因为在app.get()回调函数中,运行了这两个函数,
res.json({mssg: "welcome to the api"});
和db.collection('books').find()
这两个函数都是异步函数,所以是并行运行的,当节点遇到
db.collection().find()
时,节点开始异步处理,并转到下一行,即res.json()
方法。当
db.collection().find()
完成时(因为它是一个数据库调用,执行起来需要时间),res.json()
应该已经完成了它的执行,并且已经发送了响应。因此,误差为
"Cannot set headers after they are sent to the client"