'cannot set header before they are sent to client error

I am facing error while showing JSON response.

My code is here.

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");
})

showing Cannot set headers after they are sent to the client



Solution 1:[1]

I think error message is Cannot set headers after they are sent to the client, not before. It means that you already sent response back to the client. Just remove res.send("done"); this line.

But, be careful about other case like below. You'll also get 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})
})

So, you should add return in front of res.status(200).json({success: true}) like below.

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

Then, it'll not show up Cannot set headers after they are sent to the client this error message.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1