I would like to separate the router.get () from queries from sql queries, but I had this error, when I declare the direct function as parameter of router.get () function it works.
User.js
const express = require('express');
const router = express.Router();
const database = require('../queries/userQueries');
router.get('/users',database.getAllUsers);
module.exports = router;
userQueries.js
function getAllUsers(req, res, next) {
res.locals.connection.query('SELECT * from usuarios',
function (error, results, fields) {
if (error){
res.send(error);
return;
}
res.send(results);
});
};
module.exports = getAllUsers;
Error: Route.get() requires a callback function but got a [object Undefined] at Route.(anonymous function) [as get] (/home/antonio/achaiAPI/node_modules/express/lib/router/route.js:202:15) at Function.proto.(anonymous function) [as get] (/home/antonio/achaiAPI/node_modules/express/lib/router/index.js:510:19) at Object. (/home/antonio/achaiAPI/api/routes/user.js:11:8) at Module._compile (internal/modules/cjs/loader.js:678:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10) at Module.load (internal/modules/cjs/loader.js:589:32) at tryModuleLoad (internal/modules/cjs/loader.js:528:12) at Function.Module._load (internal/modules/cjs/loader.js:520:3) at Module.require (internal/modules/cjs/loader.js:626:17) at require (internal/modules/cjs/helpers.js:20:18)
You're assigning the function getAllUsers
itself to the module.exports
, not to a property of module.exports
. So, when you import it with require
, that resolves to said function , not an object with that function as one of its properties.
Try assigning the imported object to a variable name representing the function instead:
const express = require('express');
const router = express.Router();
const getAllUsers = require('../queries/userQueries');
router.get('/users', getAllUsers);
module.exports = router;
You would use
const database = require('../queries/userQueries');
router.get('/users',database.getAllUsers);
when your userQueries.js
had assigned the function to a property of the exports
:
module.exports.getAllUsers = function getAllUsers( ...
getAllUsers is already a function,so you can Use directly. change router.get('/users',database.getAllUsers);
to router.get('/users',database);
. you can yet return an object in userQueries.js
file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.