在我的express.js应用程序中,我按照以下方式组织我的路线
routes / comment.js(处理所有评论路线)
var express = require('express');
var router = express.Router();
var comment = require('../controller/comment');
router.route('/new').get(comment.create);
module.exports = router;
routes / post.js(处理所有帖子路线)
var express = require('express');
var router = express.Router();
var post = require('../controller/post');
router.route('/new').get(post.create);
module.exports = router;
我就像这样包含在 app.js 文件中
//need to include these declarations into another file and include that file here
//eg: require('config/main-routes');
/*
routes like comment/new
*/
var comment = require('./routes/comment');
app.use('/comment',comment);
/*
routes like post/new
*/
var post = require('./routes/post');
app.use('/post',post)
这样可以正常工作,但是我希望将其包含在另一个文件中,让我们说config/route-main.js
并将其链接到app.js
文件
我该怎么做?
答案 0 :(得分:4)
app.js
中的包括
var routes = require('./config/route-main');
app.use('/',routes);
和route-config.js
var express = require('express');
var router = express.Router();
var comment = require('./routes/comment');
var post = require('./routes/post');
router.use('/comment',comment);
router.use('/post',post)
module.exports = router
点击此链接http://katieleonard.ca/blog/2016/nested-routes-with-expressjs/
答案 1 :(得分:0)
您的app.js
文件:
const Express = require('express');
const app = Express();
const Routes = require('./routes');
app.use('', Routes);
您的routes.js
文件:
const Express = require('express');
const Router = Express.Router();
const UsersController = require('./controllers/usersController');
Router.post('/users', UsersController.CreateUser);
module.exports = Router;
您的usersController.js
文件:
const CreateUser = (req, res, next) => {
// DO STUFF HERE
}
module.exports = {
CreateUser
}