"Typeerror: Crud.Select_products is not a Function", I’m getting this error when trying to access a method from an exported class in Nodejs

Asked

Viewed 22 times

0

File server.js

var express = require('express');
var Crud = require('./database/Crud');
var app = express();


app.get('/api/home', function(req, res){
    let results = Crud.Select_products();
    res.send(results);

});

app.listen(5000, () => console.log('Escutando na porta 5000'));

Arquivo Crud.js

var Connect = require('./Connect');

class Crud {

    constructor(){
        Connect.Connecting();
    }

    Select_products(where){
        if(where !== undefined){
            let sql = 'Select * from produtos where id_produto = ?';
            Connect.query(sql, [where], function(err, result){
                if(err) throw err;
                return result;
            });
        }else{
            Connect.query('Select * from produtos', function(err, result){
                if(err) throw err;
                return result;
            });
        }
    }
}

module.exports = Crud;

Error:

TypeError: Crud.Select_products is not a function
    at C:\xampp\htdocs\react\crud\server.js:7:24
    at Layer.handle [as handle_request] (C:\xampp\htdocs\react\crud\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\xampp\htdocs\react\crud\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\xampp\htdocs\react\crud\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\xampp\htdocs\react\crud\node_modules\express\lib\router\layer.js:95:5)
    at C:\xampp\htdocs\react\crud\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\xampp\htdocs\react\crud\node_modules\express\lib\router\index.js:335:12)
    at next (C:\xampp\htdocs\react\crud\node_modules\express\lib\router\index.js:275:10)
    at expressInit (C:\xampp\htdocs\react\crud\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (C:\xampp\htdocs\react\crud\node_modules\express\lib\router\layer.js:95:5)
  • I believe what you want is module.exports = new Crud();

1 answer

0

In the Crud class, you should put the word 'Static' in the Select_product method so that you can use this method without having to instantiate the class. Would look like this:

class Crud {
 constructor(){
    Connect.Connecting();
 }

 static Select_products(where){
    if(where !== undefined){
        let sql = 'Select * from produtos where id_produto = ?';
        Connect.query(sql, [where], function(err, result){
            if(err) throw err;
            return result;
        });
    }else{
        Connect.query('Select * from produtos', function(err, result){
            if(err) throw err;
            return result;
        });
    }
}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.