Search code examples
javascriptexpressbody-parser

[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - Error when trying request


I have this error doing a GET request through postman, the request is a simple SELECT query:

(node:4804) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:558:11)
at ServerResponse.header (C:\Users\lurrechaga\source\repos\Infraestructuras\InfraestructurasAPI\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\Users\lurrechaga\source\repos\Infraestructuras\InfraestructurasAPI\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\lurrechaga\source\repos\Infraestructuras\InfraestructurasAPI\node_modules\express\lib\response.js:267:15)
at C:\Users\lurrechaga\source\repos\Infraestructuras\InfraestructurasAPI\SensoresControll\api.js:40:18
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:4804) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4804) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I´ve been looking for this error and found people missing the return, having more than one async functions thrown or missing try catch, I coudn`t find a solution for me.

Im using express, body-parser and SQL server Express on local machine

Here is the code that is getting used when the request is made:

Request:

http://localhost:8090/api/grafico/datos/temperatura/medicionAire/2059E7

API.js:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use('/api', router);

router.use((request, response, next) => {
console.log('middleware');
console.log(next());
next();
});

router.route('/grafico/datos/:medicion/:tipoMedicion/:id').get((request, response) => {
console.log("graficodato");
Db.getMedicionGrafico(request.params.medicion, request.params.tipoMedicion, request.params.id).then((data) => {
    response.json(data);
})})

FunctionAPI.js:

var config = require('./dbconfig');
const sql = require('mssql');
.
.
.
async function getMedicionGrafico(medicion, tipoMedicion, id) {
try {
    console.log("agetmedG");
    
    let pool = await sql.connect(config);
    let medicionSensor = await pool.request()
        .input('input_medicion', sql.VarChar, medicion)
        .input('input_tipoMedicion', sql.VarChar, tipoMedicion)
        .input('input_id', sql.VarChar, id)
        .query("SELECT TOP 100  " + medicion + " FROM " + tipoMedicion + " WHERE @input_id = id ORDER BY fecha DESC;");
    return medicionSensor.recordsets;
}
catch (error) {

    console.log(error);
}}

Config:

const config = {
user: 'RealUSer', // sql user
password: 'RealPasswordForsure', //sql user password
server: 'localhost', 
database: 'SensoresAire',
options: {
    trustedconnection: true,
    enableArithAbort: true,
    instancename: 'SQLEXPRESS'  // SQL Server instance name
},
port: 1433
}

module.exports = config;

Solution

  • Remove console.log(next()); from your api.js. Even though it is inside console.log, the next() function is consumed, and then on the another line you try to consume it second time. And that's that problem.