ZijianHe / koa-router

Router middleware for koa.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

router.get() throw an error : `middleware` must be a function

M6ZeroG opened this issue · comments

node.js version: 9.11.1
npm version: 6.1.0
koa-router version: 7.4.0
koa version: 2.7.0

Error message middleware must be a function not object was shown when a Promise function being the second parameter of router.get() ,source code like this :

//index.js

const Koa = require('koa');
const router = require('koa-router')();
const pfunc = require('./pfunc');

const app = new Koa();

app.use(async (ctx, next) => {

    await next();

});

.......

router.get('/test', pfunc);

......

app.use(router.routes());
app.listen(80);
//pfunc.js

async function pfunc(ctx, next){
....
await ...;
....

}

module.exports = {
    pfunc
};

This mostly because of this

koa-router/lib/layer.js

Lines 38 to 44 in 590df78

if (type !== 'function') {
throw new Error(
methods.toString() + " `" + (this.opts.name || path) +"`: `middleware` "
+ "must be a function, not `" + type + "`"
);
}
}, this);

So,how can I require an Promise function form one particular file to be the second parameter of the router.get() in one another file?

const { pfunc } = require('./pfunc');
// pfunc is the pfunc property from the export

// instead of 

const pfunc = require('./pfunc');
// pfunc is the exported object