Reputation: 281
I have not found a question with a similar setup... how do I fix this?
I'm using node, express routing, request to call a token from an api, and async series to keep everything clean. I simplified the code by only showing one function in the async series.
routes.js
var express = require('express')
var router = express.Router()
var isAuthenticated = require("./passportAuth.js")
var tokens = require('./tokens')
module.exports = function() {
router.get('/allTokens', isAuthenticated, tokens())
return router
}
./tokens.js
var request = require("request")
var async = require('async')
module.exports = function(req, res, next) {
var allTokens = function(callback) {
request('url', function(err, res, body) {
if(err) return callback(err, null)
return callback(null, 'success')
})
}
var asyncFinally = function(err, results) {
if(err) return next(err)
res.send(results)
}
async.series([allTokens], asyncFinally)
}
Error message
Route.get() requires callback functions but got a [object Undefined]
Upvotes: 1
Views: 1852
Reputation: 707916
You are prematurely calling the tokens()
function rather than just passing a reference to it. Change this:
router.get('/allTokens', isAuthenticated, tokens())
to this:
router.get('/allTokens', isAuthenticated, tokens)
Remember that any time you put ()
after a function name that means to call it now (immediately). Any time you just pass the function name by itself, that just passes a reference to the function that can be called later at the appropriate time (that's what you want here). This is a very common mistake.
Since calling tokens()
returns undefined
, that is what you end up passing to router.get()
and thus why you get the specific error message you see.
Upvotes: 1
Reputation: 816
The router is expecting a function value but you are passing in an invoked function tokens(). Try just tokens.
Upvotes: 2