BobTheDuckLing
BobTheDuckLing

Reputation: 63

Route.post() requires a callback function but got a [object Undefined] but it return a function

I know the question have been posted several times, and always it's a basic mistake, i already had this issue and always it was a mistake the kind of the already posted question.

It's like the 6th server i make this way, and this time i have no clue why it consider that not being a function.

here is the error displayed on the console

the error occur here

const router = require('express').Router();

module.exports = (api) => {

   router.post('/',
       api.middlewares.ensureAuthenticated,
       api.middlewares.bodyParser.json(),
       api.middlewares.agentDispenser.createMyAgent,
       api.actions.hub);

   return router;
}

when i comment

api.middlewares.agentDispenser.createMyAgent

it doesn't crash

my middleware index look like that

module.exports = (api) => {
    api.middlewares = {
        bodyParser: require('body-parser'),
        ensureAuthenticated: require('./ensureAuthenticated'),
        agentDispenser: require('./agentDispenser')
    };
};

and agentDispenser look like this

const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
var agent;

module.exports = (api) => {

    function createMyAgent(req, res, next) {
        agent = new WebhookClient({ req, res })
        return next()
    }

    function getMyAgent() {
        return agent
    }

    return {
        createMyAgent,
        getMyAgent
    }
}

as i said, i use the same syntaxe/structure on many project, and it work, so i dont really know what is the probleme, i have read a lot of topic on that, a lot are about a forgoten return or missing (api)... but here i dont know

Thanks for your help in advance

EDIT: shame on me...

Upvotes: 0

Views: 319

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174947

api.middlewares.agentDispenser.createMyAgent is undefined because api.middlewares.agentDispenser is a function that accepts api and returns your middleware namespace, and is not the namespace itself.

I'm guessing you want something like

module.exports = (api) => {
    api.middlewares = {
        bodyParser: require('body-parser'),
        ensureAuthenticated: require('./ensureAuthenticated'),
        agentDispenser: require('./agentDispenser')(api),
    };
};

Upvotes: 1

Related Questions