"TypeError: Crud.Select_products is not a function", I am getting this error when trying to access a method of an exported class, in NodeJS

0

Server.js file

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'));

Crud.js file

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)
    
asked by anonymous 02.01.2019 / 20:48

1 answer

0

In the class Crud, you should put the word 'static' in the Select_product method so that you can use this method without having to instantiate the class. It 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;
        });
    }
}
}
    
05.01.2019 / 15:35