【问题标题】:cannot set header before they are sent to client error在将标头发送到客户端之前无法设置标头错误
【发布时间】:2022-02-10 21:42:08
【问题描述】:

我在显示 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

【问题讨论】:

  • "showing cannot set header before they are sent to client" - 你到底是什么意思?您认为自己的行为不正确的确切症状是什么?
  • 你不能同时使用.json.send

标签: javascript node.js express


【解决方案1】:

我认为错误消息是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这个错误信息了。

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 2020-07-11
    相关资源
    最近更新 更多