我正在尝试学习 Nodejs 和 MongoDb。所以我所做的就是创建一个简单的网页,它将报价保存到 MongoDb 并检索它。但我无法从 MongoDb 获取数据,我收到 Nodejs 错误,上面写着
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the
client
at ServerResponse.setHeader (_http_outgoing.js:485:11)
at ServerResponse.writeHead (_http_server.js:269:21)
at C:\Hritik\programming\Advanced Web\FirstMern\server.js:18:25
at processTicksAndRejections (internal/process/task_queues.js:94:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
< Server.js>
const express = require('express');
const bodyParser = require('body-parser')
const MongoClient = require('mongodb').MongoClient
const app = express();
MongoClient.connect('mongodb+srv://{Username}:{password}@cluster0.vmmbl.mongodb.net/<dbname>?retryWrites=true&w=majority', { useUnifiedTopology: true })
.then(client => {
console.log('Connected to Database')
const db = client.db('star-wars-quotes')
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', (req, res) => {
res.sendFile('C:/Hritik/programming/Advanced Web/FirstMern' + '/index.html')
db.collection('quotes').find().toArray()
.then(results => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.render('index.ejs', { quotes: results })
res.end();
})
.catch(error => console.error(error))
});
app.post('/quotes', (req, res) => {
db.collection('quotes').insertOne(req.body, (err, result) => {
if (err) return res.end();
console.log('saved to database')
res.redirect('/')
})
});
app.listen(3000, function() {
console.log('listening on 3000')
})
})
.catch(console.error)
删除调用
res.end()
之后的 res.render()
,因为 res.render()
已经结束了请求,并且尝试再次结束它会导致出现警告消息。
Response.prototype.end
和Response.prototype.render
都结束请求。显然您不能发送标头两次(每个响应都发送标头),因此删除 res.end()
。
我发现非常有用的一种方法是,当您发送响应或渲染某些内容时,您可以将 return 放在前面,这样函数就不会在 return 语句之后执行:-
return res.status(200).json({success:true, msg:"something good happened"})
简短的答案是, 一旦执行了
res.render("...")
行,请勿尝试写入 res.send("...")
或 res.end()
,因为 res.render() 已经结束了请求。