Leo Messi
Leo Messi

Reputation: 6186

API call works fine after npm start but crashes at refresh

There is an API call on http://localhost:9000/testAPI.

In bin/www:

var port = normalizePort(process.env.PORT || '9000');
app.set('port', port);

in routes/index.js:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

in routes/testAPI.js:

var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./db/ocs_athletes.db');

router.get('/', function (req, res, next) {
  db.serialize(function () {
    db.all('SELECT athlete_id, name, surname FROM Athlete', function (
      err,
      row
    ) {
     return res.send(row);
    });
  });

  db.close();
});

module.exports = router;

When the command npm start is run, the API works, going to http://localhost:9000/testAPI shows a JSON containing the data.

The problem appears when the page is refreshed. It says Page cannot be reached and in terminal it throws this error:

GET /testAPI 304 20.628 ms - -
undefined:0



Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (/home/rares/Documents/Projects/ocsApp/api/node_modules/express/lib/response.js:767:10)
    at ServerResponse.json (/home/rares/Documents/Projects/ocsApp/api/node_modules/express/lib/response.js:264:10)
    at ServerResponse.send (/home/rares/Documents/Projects/ocsApp/api/node_modules/express/lib/response.js:158:21)
    at Statement.<anonymous> (/home/rares/Documents/Projects/ocsApp/api/routes/testAPI.js:12:11)
    at Statement.replacement (/home/rares/Documents/Projects/ocsApp/api/node_modules/sqlite3/lib/trace.js:25:27) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Is there a way to solve this problem?

Upvotes: 0

Views: 257

Answers (5)

Swale Khan
Swale Khan

Reputation: 1

Only change loacalhost name weather react or node.js

Like loacalhost:3000 Then you will have to change 4000

Upvotes: 0

Leo Messi
Leo Messi

Reputation: 6186

This problem appears in this case because of db.close(), that line shouldn't be in the code.

So it would work fine if it is like this:

var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./db/ocs_athletes.db');

router.get('/', function (req, res, next) {
  db.serialize(function () {
    db.all('SELECT athlete_id, name, surname FROM Athlete', function (
      err,
      row
    ) {
     return res.send(row);
    });
  });
});

module.exports = router;

Upvotes: 1

Yves Kipondo
Yves Kipondo

Reputation: 5623

You are geting that error because there are some error in you request handler

You are using db.each method to access result of the question which you performed. The purpose of that method is to allows you to execute some special callback as define in the documentation

The each() method executes an SQL query with specified parameters and calls a callback for every row in the result set.

As your needs in your request handler is to return as the body the result of the query you should use db.all instead of db.each. There isn't any special code which perform some treatment on each row of the result. You can simple return the entire set of rows.

The fact that in the callback of the db.each you are using res.send this presume as many rows the query you performed to you sqlite database your can will try to rerun `res.send. When this is performed on the first row of the query result It work perfectly but the second time It will try to resent the result which seam to override the response which as already been sent to the browser and It will trigger that error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:526:11)

So to fix that you change your code like this

db.all('SELECT athlete_id, name, surname FROM Athlete', function(err, rows) {
   res.send(rows);
})

Upvotes: 0

Babak Abadkheir
Babak Abadkheir

Reputation: 2358

this error happens basically when your function is keeping continue processing the execution after your res.send() . you must use return for avoiding that :

return res.send()

Upvotes: 1

Muirik
Muirik

Reputation: 6289

The error "Error: Can't set headers after they are sent." is telling you that you're already in the body or completed state, but that some function tried to set a header or statusCode. When this error occurs, look for something that tries to send a header AFTER some of the body has been written. This could be callbacks that end up being called twice, or an error that arises after the body is sent.

Upvotes: 0

Related Questions