Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
How to solve reference error response data is not defined in MEAN stack api project?

I’m trying to build an API with mean stack, but when I test the endpoint with a get request using postman, I get the following error:

ReferenceError: studentData is not defined
at module.exports.StudentsGetAll (F:\MEAN\api\controllers\students.controllers.js:13:11)
at Layer.handle [as handle_request] (F:\MEAN\node_modules\express\lib\router\layer.js:95:5)
at next (F:\MEAN\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (F:\MEAN\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (F:\MEAN\node_modules\express\lib\router\layer.js:95:5)
at F:\MEAN\node_modules\express\lib\router\index.js:281:22
at Function.process_params (F:\MEAN\node_modules\express\lib\router\index.js:335:12)
at next (F:\MEAN\node_modules\express\lib\router\index.js:275:10)
at Function.handle (F:\MEAN\node_modules\express\lib\router\index.js:174:3)
at router (F:\MEAN\node_modules\express\lib\router\index.js:47:12)

However if send a second get request the studentData response is returned as I want it. What am I doing wrong?

Students.controllers.js

var dbconn = require('../data/dbconnection.js');


module.exports.StudentsGetAll = function( req, res) {

dbconn.open();
console.log('GET the Students');

res
.status(200)
.json(studentData);
};

Dbconnection.js

var sql = require('mssql');
var query = require('./queries.js');
var dburl = 'mssql://*****:****@**.**.*.**/******/*******';

function open() {
  var conn = new sql.Connection(dburl);
  var req = new sql.Request(conn);

  conn.connect(function (err) {
      if (err) {
        console.log(err);
        return;
      }
      console.log("Database Connection established");
      req.query(query.getAllQuery, function (err, recordset) {
        if (err) {
          console.log(err);
        }
        else {
          studentData = recordset;
        }
      });
  });
}

module.exports = {
  open : open
};

How can define the response data before it actually exists? I am confused can anyone explain where I'm going wrong please?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

During the first try, your code will respond before the database connection was established. The second time would work better because the db connection was established already after the first try.

A database connection will block the I/O. Meaning that you should implement a callback function to be performed after the connection is made and then respond with the data retrieved.

I would re-write the Students.controllers to the following:

// Students.controllers.js

var dbconn = require('../data/dbconnection.js');


module.exports.StudentsGetAll = function( req, res) {

   var getStudentData = function(studentData){
        res
        .status(200)
        .json(studentData);
        };

    dbconn.open(getStudentData);
    console.log('Getting Students Records');
}

//Dbconnection.js

var sql = require('mssql');
var query = require('./queries.js');
var dburl = 'mssql://*****:****@**.**.*.**/******/*******';

function open(callback) {
  var conn = new sql.Connection(dburl);
  var req = new sql.Request(conn);

  conn.connect(function (err) {
      if (err) {
        console.log(err);
        callback({error: err}); // Respond back with error
        return;
      }
      console.log("Database Connection established");
      req.query(query.getAllQuery, function (err, recordset) {
        if (err) {
          console.log(err);
          callback({error: err}); // Respond back with error
        }
        else {
          // Added Callback
          callback(recordset); // Respond back with data set
        }
      });
  });
}

module.exports = {
  open : open
};
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda