在将标头发送到客户端之前无法设置标头错误



我在显示JSON响应时遇到错误。

我的代码在这里。

app.get('/api/:id/:uid?',(req,res)=>{//? mean optional parameter
console.log(req.params);// to get parameter in console
const id=req.params.id*1;
console.log(id);
const tour=tours.find(el=>el.id===id);
res.status(200).json({
"staus":"success",
"tours":tour
})
res.send("done");
})

显示Cannot set headers after they are sent to the client

我认为错误消息是Cannot set headers after they are sent to the client,而不是before。这意味着您已经将响应发送回客户端。只需删除此行的res.send("done");

但是,要小心下面的其他情况。您还将获得Cannot set headers after they are sent to the client

app.get("/path", (req, res) => {
some_condition = true
if (some_condition) {
res.status(200).json({success: true})
}
res.status(200).json({success: false})
})

因此,您应该在res.status(200).json({success: true})前面添加return,如下所示。

app.get("/path", (req, res) => {
some_condition = true
if (some_condition) {
return res.status(200).json({success: true})
}
res.status(200).json({success: false})
})

然后,它将不会显示Cannot set headers after they are sent to the client此错误消息。

最新更新