2017-01-20 26 views
-1

在routes/index.js上,如果我离开module.exports = routes,它工作正常。 但如果我将其更改为以下允许多个文件,然后我得到一个中间件错误:快递中间件问题

module.exports = { 
    routes 
}; 

var app = express(); 
const routes = require('./routes'); 
const port = process.env.PORT || 3000; 

app.use(bodyParser.json()); 
app.use('/', routes); 



app.get('/', (req, res) => { 
    res.send('Please visit: http://domain.com'); 
    }, (err) => { 
    res.send(err); 
}); 

//routes/index.js

const routes = require('./MainRoutes'); 
module.exports = routes; 

// routes/Main Routes.js

const routes = require('express').Router(); 
routes.post('/main', (res, req) => { 
    //code here works 
}); 
module.exports = routes; 

错误是:Router.use()需要中间件功能,但得到'+ gettype(fn));

回答

0

MainRoutes.js出口快件路由器对象,中间件就会明白,如果你做的很好

module.exports = routes; // routes/index.js 

但是,当你做

module.exports = { 
    routes 
}; 

您现在的嵌套路由器对象在另一个对象,哪些中间件无法理解。

在主服务器上的文件,你可以做

const {routes} = require('./routes'); 

正确获取路由器对象。

0

修改routes/index.js为:

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

routes.use('/main', require('./MainRoutes')); 

// Put other route paths here 
// eg. routes.use('/other', require('./OtherRoutes')) 

module.exports = routes; 

修改Main Routes.js为:

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

routes.post('/', (res, req) => { 
    // route controller code here 
}); 

module.exports = routes; 

希望这有助于你。

+0

在index.js如果我改变module.exports = {routes};那么我得到相同的错误Router.use()需要中间件功能,但得到....我已经做了所有的更改和工作相同,只是不是如果我想从index.js文件多个出口...? – Mike

+0

第一个......它的'module.exports =路由;'和**不** ** module.exports = {routes};'。在中间路由模块中,你应该使用'routes.use',在routes-controller中你必须使用'routes.get'(或者post,put等)。另外请注意,为了简化我将路由路径'/ main'移动到中间路由模块,并在控制器中处理'/'。你可以扭转它,在你这个简单的情况下,它不会有任何区别。 –