0

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?

Prabir Choudhury
  • 143
  • 1
  • 18

2 Answers2

2

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

Sebastien H.
  • 6,818
  • 2
  • 28
  • 36
  • hi @SebastienH please take a look at the edited portion of main post under EDIT; – Prabir Choudhury Nov 03 '22 at 14:43
  • 1
    @PrabirChoudhury the edit section is a different issue than the original question. you should probably return the `recordset` property of your `recordset` result parameter. – Sebastien H. Nov 03 '22 at 16:05
  • 1
    hi @SebastienH yep --- I opened a separate question: https://stackoverflow.com/questions/74305542/fetched-record-from-mssql-database-being-displayed-twice-in-postman-response-win – Prabir Choudhury Nov 03 '22 at 16:07
  • 1
    btw i would recommend applying your own standard for the API output format, with props like `{ message, data, status, errors etc..}` – Sebastien H. Nov 03 '22 at 16:07
  • yes, it works if I put ---> return res.send(recordset.recordset[0]); returns the fetched data 1ce as expected. – Prabir Choudhury Nov 03 '22 at 16:17
1

When you connect successfully to the database, and the query returns results without error, you are sending the results back with:

res.send(recordset)

But also, regardless if the connection with the database is established or not, you are sending back a message:

return res.send("Record fetched for selected player!");

res.send() can only be called only once per request.

Paul
  • 55
  • 1
  • 9