简体   繁体   中英

Router.use() requires middleware function but got an Object

I was experimenting with Express 4's new Router and was wondering how one would go about doing below...

I made a file named app.js under a routes folder containing, basically, this:

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

module.exports = (function() {

    router.get('/testindex', function(req, res) {
        res.render('testindex');
    })

    return router;

})();

In my server.js file this works as expected...

var appRouter = require('./routes/app');
var apiRouter = require('./routes/api/v1.js');
app.use('/', appRouter);
app.use('/api/v1',apiRouter);

I was hoping to do something like this, but I got the error I mentioned in the title...

var router = {
    api: {
        v1: require('./routes/api/v1'),
        v2: (...)
    },
    app: require('./routes/app')
};

app.use('/api/v1', router.api.v1);
app.use('/api/v2', router.api.v2);
app.use('/', router.app);

What am I not understanding?

When trying to reproduce your issue, there is no problem when I remove this statement:

app.use('/api/v2', router.api.v2);

So, there is probably something wrong with the way you defined the v2 property (which you did not flesh out in your question).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM