I am trying to get data by Id records saved in mssql database. for eg. I am forming a get request in postman like this: localhost:3200/api/v1/players Problem is I am getting error displayed as follows:
node:_http_outgoing:576
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Why is it so? Is it because some other query is also running when I am visiting that endpoint?
My code for querying by data:
const getPlayerById=async(req, res, next)=>
{
try
{
const id = req.params.id;
sql.connect(config, function(err)
{
if(err)
{
console.log(err);
}
else
{
var req=new sql.Request();
var player=req.input('input_parameter', sql.BigInt, id)
.query("select distinct * from players WHERE Id=@input_parameter", function(err, recordset)
{
if(err)
{
console.log("Error while querying for Id!: "+err)
}
else
{
res.send(recordset);
}
});
}
return res.send("Record fetched for selected player!");
});
}
catch(error)
{
res.status(400).send(error.message);
}
}
In my main server.js I have wired up
app.use('/api/v1', playerRoutes.routes);
In router file:
router.get('/players/:id', playerControll.getPlayerById)
The record being displayed in my postman response window is like:
Could not send request Error: connect ECONNREFUSED 127.0.0.1:3200
EDIT********** Now the query is working, but I am getting the fetched record being displayed twice in a nested format!!
Like this->
{
"recordsets": [
[
{
"Id": 6,
"player_code": "P006",
"player_name": "Petr Cech",
"player_club": "Chelsea",
"player_position": "Goalkeeper"
}
]
],
"recordset": [
{
"Id": 6,
"player_code": "P006",
"player_name": "Petr Cech",
"player_club": "Chelsea",
"player_position": "Goalkeeper"
}
],
"output": {},
"rowsAffected": []
}
What's the glitch now?? Why is it showing like this?
You are getting this error, simply because the res.send(recordset);
line is executed before the return res.send("Record fetched for selected player!");
Maybe you should add a return
keyword to have return res.send(recordset);