cuando trato de usar response.send() siempre muestra un mensaje Error [ERR_HTTP_HEADERS_SENT]: No se pueden establecer encabezados después de enviarlos al cliente. He proporcionado el código. Por favor, ayúdenme a solucionar este error.
/** * Post is used to create new items * Put is used to update the items * Listen is used to run the server * Delete is used to delete an item */ const express = require('express'); const bodyParser = require('body-parser'); const axios = require('axios').default; const { response } = require('express'); const app = express(); app.use(bodyParser.urlencoded({extended:false})); app.use(bodyParser.json()); var city = 'delhi'; app.put('/enter_data',(req,res)=>{ city = req.body.City; if(city === "" || !city){ res.status(500).send({error: "Write something"});} else { res.send("Now you can see the temperature"); } }) app.get('/show_temp',(req,res)=>{ var sample = "https://api.openweathermap.org/data/2.5/weather?q="+city+'&units=metric&appid=bb16c5275f7a3c1439973f71e4dc811f'; res.send("Running"); axios.get(sample) .then(response => { var t = "Temperature in "+city+" is "+String(response.data.main.temp)+"°C" if(t) { res.status(200).send(t); } }) .catch(error => { console.log(error); //res.status(503).send({status: 1, message: "Messages not available!"}); }) }); app.listen(5000,()=>{ console.log("Port Running"); })No puede enviar una respuesta a una solicitud varias veces como esta; Una solicitud debe equivaler a una respuesta.
app.get('/show_temp',(req,res)=>{ var sample = "https://api.openweathermap.org/data/2.5/weather?q="+city+'&units=metric&appid=bb16c5275f7a3c1439973f71e4dc811f'; res.send("Running"); // Here you are sending a response of "Running" to the client axios.get(sample) .then(response => { var t = "Temperature in "+city+" is "+String(response.data.main.temp)+"°C" if(t) { res.status(200).send(t); // Here is where you are sending you're actual response and thus triggering the error. } }) .catch(error => { console.log(error); //res.status(503).send({status: 1, message: "Messages not available!"}); }) });Refactorizando esto, una solución sería:
app.get('/show_temp',(req,res)=>{ var sample = "https://api.openweathermap.org/data/2.5/weather?q="+city+'&units=metric&appid=bb16c5275f7a3c1439973f71e4dc811f'; axios.get(sample) .then(response => { var t = "Temperature in "+city+" is "+String(response.data.main.temp)+"°C" if(t) { res.status(200).send(t); } }) .catch(error => { console.log(error); res.status(503).send({status: 1, message: "Messages not available!"}); // This is fine so long an error is not thrown AFTER the response }) });También señalaré que definitivamente hay casos de uso para enviar diferentes respuestas para diferentes escenarios. Puede tener un paso de validación, por ejemplo, donde necesita enviar un estado 400 al cliente. En este caso, desea devolver su respuesta para evitar que se envíen otras respuestas.
Fragmento de ejemplo:
if (badData) { return res.sendStatus(400) } res.sendStatus(200)