我对Express上的异步功能有疑问。我从数据库中获取一些JSON,我收到以下错误:错误:发送后无法设置标头。
我已经阅读了一些关于它的内容,它似乎与具有完成状态或类似功能的功能有关。
我有以下代码,它崩溃了我的应用程序:
router.get('/home', isAuthenticated, function(req, res){
atendimentos.find({}, function(err, atendimentos) {
if(!err){
console.log(atendimentos);
return res.json(atendimentos);
}
})
res.render('home', {user: req.user});
})
但后来我改为这段代码:
router.get('/home', isAuthenticated, function(req, res){
//Added async to the function
atendimentos.find({}, async function(err, atendimentos) {
if(!err){
console.log(atendimentos);
return res.json(atendimentos);
}
})
res.render('home', {user: req.user});
})
应用程序停止崩溃,但错误仍在继续。我不知道为什么。也许我可以得到一些帮助处理这个?
谢谢
res.json()
发送响应(格式为JSON)。
res.render()
发送响应(使用其他格式化方法)。
您不能向同一请求发送两个回复。
选一个。
来自Docs:
res.render
呈现视图并将呈现的HTML字符串发送到客户端。
res.json
发送JSON响应。此方法使用JSON.stringify()发送响应(具有正确的内容类型),该响应是转换为JSON字符串的参数。
因此,如上所述,您发送了两个回复。如果你想要的是在你的视图中有atendimentos
数据,你可以将它作为对象的属性传递给res.render
,例如:
router.get('/home', isAuthenticated, function(req, res){
//Added async to the function
atendimentos.find({}, async function(err, atendimentos) {
if(!err){
console.log(atendimentos);
res.render('home', {user: req.user, atendimentos});
}
});
});
或者您可以使用fetch
,XMLHttpRequest
或任何其他方式进行单独的API调用。
附: async
与你的问题无关,它停止崩溃的原因是未处理的拒绝不会使Node崩溃,这将在未来的版本中发生变化。