javascriptnode.jsapiexpressnpm

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! api@0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the api@0.0.0 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?


Solution

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