Estoy enfrentando un error al mostrar la respuesta JSON.
Mi código está aquí.
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"); }) mostrando Cannot set headers after they are sent to the client
Creo que el mensaje de error es Cannot set headers after they are sent to the client , no before . Significa que ya envió una respuesta al cliente. Simplemente elimine res.send("done"); esta línea.
Pero, tenga cuidado con otros casos como el siguiente. También obtendrá 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}) }) Por lo tanto, debe agregar return delante de res.status(200).json({success: true}) como se muestra a continuación.
app.get("/path", (req, res) => { some_condition = true if (some_condition) { return res.status(200).json({success: true}) } res.status(200).json({success: false}) }) Entonces, no aparecerá Cannot set headers after they are sent to the client este mensaje de error.