我正在尝试将我的所有路由文件集中到一个索引文件中,并将该索引路由文件放在我的主应用程序文件中。我正在尝试关注this thread
我已经添加了app.js文件。以及下面的路线/文件夹:
当我尝试获取如下所述的任何网址时,它显示404错误。
app.js:
const indexRouter = require('./routes/index');
app.use('/', indexRouter);
路由文件:
-- index.js
-- author.js
-- book.js
index.js:
const express = require('express');
const router = express.Router();
// Get Home Page of The Web Application
router.get('/', function(req, res) {
res.send('Library Home Page');
});
router.use('/author', require('./author').router);
router.use('/book', require('./book').router);
module.exports = router;
author.js:
const express = require('express');
const router = express.Router();
var AuthorController = require('../controllers/authorController');
router.get('/', AuthorController.authorList);
router.get('/:id', AuthorController.authorDetail);
router.get('/create', AuthorController.authorCreateForm);
module.exports = router;
book.js:
const express = require('express');
const router = express.Router();
var BookController = require('../controllers/bookController');
router.get('/', BookController.bookList);
router.get('/:id', BookController.bookDetail);
router.get('/create', BookController.bookCreateForm);
module.exports = router;
我要按如下方式访问网址:
Home:
/
Author:
/author/
/author/1
/author/create
Book:
/book/
/book/1
/book/create
答案 0 :(得分:3)
module.exports = router
是默认导出,因此require('./author').router
指的是路由器上未定义的属性,它应该是:
router.use('/author', require('./author'));
在服务器条目中:
app.use(indexRouter); // No `'/'` as first param