gothinkster / node-express-realworld-example-app

3.58k stars 1.61k forks source link

Route.get() requires callback functions but got a [object Undefined] #40

Open coommark opened 7 years ago

coommark commented 7 years ago

I am attempting to recreate this application from scratch. So far I have users controller in place (without the articles, profiles and tags controllers.

However when I try to run the server, I get Route.get() requires callback functions but got a [object Undefined] error. If I comment out the router.get('/user' and router.put('/user' routes, everything works okay and I can register users without problem.

I have been on this for hours. please does anyone know what the problem might be and how to fix it?

Here is complete error message:

C:\production apps\backend\node_modules\express\lib\router\route.js:202
        throw new Error(msg);
        ^
Error: Route.get() requires callback functions but got a [object Undefined]
    at Route.(anonymous function) [as get] (C:\production apps\backend\node_modules\express\lib\router\route.js:202:15)
    at Function.proto.(anonymous function) [as get] (C:\production apps\backend\node_modules\express\lib\router\index.js:510:19)
    at Object.<anonymous> (C:\production apps\backend\routes\api\users.js:9:8)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\production apps\backend\routes\api\index.js:3:17)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! backend@1.0.0 start: `node ./app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the backend@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\BenKay\AppData\Roaming\npm-cache\_logs\2017-09-07T13_43_52_191Z-debug.log
mcblum commented 6 years ago

I've got the same exact issue. Did you ever figure this out?

ghost commented 6 years ago

I´ve got the same problem

angelbrunn commented 6 years ago

check this!

https://stackoverflow.com/questions/36558909/route-get-requires-callback-functions-but-got-a-object-undefined

DaSilvaJr commented 6 years ago

i have some problem like that :(

jessicabyrne commented 6 years ago

I had the same problem. Turned out I had a call in my router.js that wasn't available anymore. When I removed it, the error went away.

surferwat commented 6 years ago

@jessicabyrne can you clarify what call that you removed? Thanks.

tonilaukka commented 6 years ago

I was missing module.exports = auth at the end of routes/api/users.js

Anindo94 commented 6 years ago

anyone please provide the solution

eawww commented 6 years ago

Check imports/requires and their respective exports for the use function's second argument and make sure they match up. In my case, I made the dumb mistake of doing a named import on a component that didn't have named exports. Example of doing it wrong: export default ReallyNeatComponent import { ReallyNeatComponent } from './ReallyNeatComponent'

Fathma commented 6 years ago

In routes.js you might have called a function which doesn't exist in controller.js. make sure you have created all the functions that you are calling at the time of setting route.

SampritiKakoty commented 6 years ago

I was getting same problem.

My authenticate file has method: exports.verifyUser = passport.authenticate('jwt', {session: false}); exports.verifyAdminUser = (req, res, next) => {

And my router file was:

uploadRouter.route('/') .get(authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { res.statusCode = 403; res.end('GET operation not supported on /imageUpload'); })

It was unable to find the function authenticate.verifyAdmin when i change it to authenticate.verifyAdminUser it worked.

So you might be missing a function which is required while setting the routes/middleware.

MRJordanGracia commented 5 years ago

Hello, could you tell me how you implemented the function of verifyAdmin, I'm having de same problem and I'm not able to see how to solve it. Regards.

shekankode commented 5 years ago

check this link out https://stackoverflow.com/questions/34853675/error-post-requires-callback-functions-but-got-a-object-undefined-not-work

hakoemmy commented 5 years ago

@eawww You made my day. I was mixing module.exporsts = auth with export default router, after I choose to use one and it works like charm..

dh360 commented 4 years ago

in my case , i write a wrong function name , it happened

proxybee commented 4 years ago

I had the same problem. Turned out I had a call in my router.js that wasn't available anymore. When I removed it, the error went away.

this worked for me too, thank you

thurnye commented 4 years ago

check your syntax in your controller, i had that problem for hrs getting pissed off. turns out it was just a syntax error " }"

Jood80 commented 4 years ago

I got the same problem, the middleware was exported that way exports.isAuthenticated = (req, res, next) => {....} when I replaced it with const isAuthenticated=(req, res, next)=>{.....}; module.exports = isAuthenticated it works for me

md1116 commented 4 years ago

anyone please provide the solution

I had the same issue and my mistake was using in express exports = {somefunctionName, anotherFunctionName}_ But looking at the above solution I did it like this and it works for me module.exports = {somefunctionName, anotherFunctionName}

zarateganso10 commented 4 years ago

i had the same issue, and my mistake was exporting the controller like a function and not a new object

module.exports = UserController wrong way

module.exports = new UserController() correct

ya332 commented 4 years ago

I had the same issue and my problem was that I added .default in my require. file_a module.exports = dosomething file_b I changed this

const dosomething = require('file_a').default

to this

const dosomething = require('file_a')

and it fixed.

ypedroo commented 3 years ago

i had the same issue, and my mistake was exporting the controller like a function and not a new object

module.exports = UserController wrong way

module.exports = new UserController() correct

Reading this i cant belive how stupid i was by loosing 2 hours on this haha, thank you dude

lucaslp16 commented 3 years ago

Obtive o mesmo problema. Eu invoquei um middleware para a rota, porem havia colocado o module.exports do middleware dentro da indentação do código, mania de ficar dando enter para dar mais espaço na tela kkk

Fiquei feliz por descobrir o problema porem puto pq perdi uns 30min procurando kkk

kamaleshsivaraj commented 3 years ago

Error: Route.get() requires a callback function but got a [object Undefined] at Route. [as get] (node_modules) path

Instead of this:

app.get('/user/all',Controller.Create); You try for:

app.get('/user/all', function(req, res){
  Controller.Create
});

it worked for me! after a 15mins

hiranyagarbh commented 3 years ago

@eawww You made my day. I was mixing module.exporsts = auth with export default router, after I choose to use one and it works like charm..

Thank you for pointing that out. I was doing the same.

yysach commented 3 years ago

anyone please provide the solution

I had the same issue and my mistake was using in express exports = {somefunctionName, anotherFunctionName}_ But looking at the above solution I did it like this and it works for me module.exports = {somefunctionName, anotherFunctionName}

thanks, I was doing the same mistake...

Gichohi-Simon commented 3 years ago

I got the same problem, the middleware was exported that way exports.isAuthenticated = (req, res, next) => {....} when I replaced it with const isAuthenticated=(req, res, next)=>{.....}; module.exports = isAuthenticated it works for me

`

this works I have tried it in my code. Thanks a lot, but do you an idea why?

malkashlomowithz commented 3 years ago

@eawww You made my day. I was mixing module.exporsts = auth with export default router, after I choose to use one and it works like charm..

Made my day too!!

Rajveerbi commented 3 years ago

just check if you are importig your functions properly on the routes and check the spellings

nurulhiidayah commented 3 years ago

in my case i accidentally put () for a middleware that did not accept params lol

amir-sdmi commented 2 years ago

check your syntax in your controller, i had that problem for hrs getting pissed off. turns out it was just a syntax error " }"

me 2 , I hate syntax errors :((((

imranfarhat commented 2 years ago

C:\Users\dell\OneDrive\Desktop\liftech\BackendLiftech\node_modules\express\lib\router\route.js:202 throw new Error(msg); ^

Error: Route.get() requires a callback function but got a [object Undefined] at Route. [as get] (C:\Users\dell\OneDrive\Desktop\liftech\BackendLiftech\node_modules\express\lib\router\route.js:202:15) at Function.proto. [as get] (C:\Users\dell\OneDrive\Desktop\liftech\BackendLiftech\node_modules\express\lib\router\index.js:510:19) at Object. (C:\Users\dell\OneDrive\Desktop\liftech\BackendLiftech\routes\wallethistory.js:19:8) at Module._compile (internal/modules/cjs/loader.js:1072:14) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10) at Module.load (internal/modules/cjs/loader.js:937:32) at Function.Module._load (internal/modules/cjs/loader.js:778:12) at Module.require (internal/modules/cjs/loader.js:961:19) at require (internal/modules/cjs/helpers.js:92:18) at Object. (C:\Users\dell\OneDrive\Desktop\liftech\BackendLiftech\app.js:32:30) at Module._compile (internal/modules/cjs/loader.js:1072:14) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10) at Module.load (internal/modules/cjs/loader.js:937:32) at Function.Module._load (internal/modules/cjs/loader.js:778:12) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12) at internal/main/run_main_module.js:17:47 [nodemon] app crashed - waiting for file changes before starting...

Jood80 commented 2 years ago

@imranfarhat you should post a snippet of your code that's complaining about too

ferisetiawan69 commented 2 years ago

Error: Route.post() requires a callback function but got a [object Object]

How to fix this?

hilmidemirtas commented 2 years ago

the problem is pageRoute or your Route.js file. Check or write again

tsmith-sdm commented 2 years ago

In my case I typod handler: as hander:

airKing05 commented 2 years ago

got the same error currently using Node.js v18.1.0 I have cloned a 9-month-old project from the git repo please help me to finger out it.

ishan-im commented 2 years ago

In the middleware I exported it as exports.userController = (req,res,next)=>{.................} I replaced it with const userController = (req,res,next) =>{...........} module.exports = userController and it worked for me :), also exports.userController = (req,res,next)=>{.................} in route folder I imported it as const user = require('./auth) and router.post('/user', user.userController) - it worked both ways 👍

For more details have a look at stack over flow and export mdn docs

Pvpasall commented 2 years ago

Hi, I got the same issue, Check if you correctely import your controller

ConradPB commented 1 year ago

Hi.. This issue actually bothered me for months so I will put my solution here to hopefully help someone.

So, I am building a backend using express and es6 class based controllers. I got this issue when I was creating the controller.

You have to make sure that u are exporting AND importing your controller correctly.

On my part I was exporting using -export default Controller- as an example. I realised that my problem happened when I was importing... you import by saying " import Controller from '../controllers/..' "

I found out that my problem was that after this step I missed something very important.. You are supposed to create an instance of the class so that u can have access to the various functions in your class.. so I had to do that by adding

const controller = new Controller()

After doing that, I had access to the functions in the class and the warning disappeared.

I hope this helps someone. Goodluck

Lanzero17 commented 1 year ago

@gothinkster

The error is in the path: C:\production apps\backend\routes\api\users.js on line 9

Check if you have a function like the following

router.get("/test-route", callback function );

for example:

router.get("/test-route", (req, res) => { return res.status(200).json({ message: "I am a test action in my item controller" }) });

in case the callback function is imported from another module, make sure you are writing the export statement correctly, for example:

//file users.js-------------

const expres = require("express") const router = expres.Router();

const ItemController = require("../controllers/item"); router.get("/test-route", callback function imported from another module );

//file that exports the callback function example.js-------------

const test = (req, res) => { return res.status(200).json({ message: "I am a test action in my item controller" }); }

//Error made //module.export is misspelled //the import will not be carried out

module.export = { test }

//The correct way to write is

module.exports= { test }

My recommendation is that you check that each sentence is written correctly

error code 3

error code 1

The code is now correct

error code 2

result

iniciado correctamente

davixie commented 1 year ago

Error: Route.get() requires a callback function but got a [object Undefined] at Route. [as get] (node_modules) path

Instead of this:

app.get('/user/all',Controller.Create); You try for:

app.get('/user/all', function(req, res){
  Controller.Create
});

it worked for me! after a 15mins

This worked for me too. Does anyone know why the first way is incorrect? It seems ok to me

katsisaac50 commented 1 year ago

Always ensure the export name is the same as the import name

anshu1016 commented 7 months ago

I encountered the same issue and resolved it by meticulously reviewing my import and export statements for every file and function. This turned out to be one of the causes leading to the problem.