在express 开发过程中路由文件过多,如果全部都定义在一起就会出现路由混乱 难以维护的问题。
因此我研究了下路由分组的问题
一级路由文件
const express = require("express")
const router = express.Router()
router.get('/myInfo1/query', (req, res) => {
res.send('我的模块')
})
module.exports = router
const express = require("express")
const router = express.Router()
router.get("/myCollect/query",(req,res)=>{
res.send("我是收藏模块")
})
module.exports = router
二级路由文件
const express = require("express")
const router = express.Router()
let myCollect = require('./module/myCollect');
let myInfo=require("./module/myInfo")
router.use("/user",myInfo)
router.use("/user",myCollect)
module.exports = router
//https://qa.1r1g.com/sf/ask/1768257291/
app.js
简洁代码
var express = require('express');
var userRouter = require('./routes/user/index');
var app = express()
app.use('/app', userRouter);
完整代码
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var userRouter = require('./routes/user/index');
// console.log("userRouter",userRouter)
// var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', indexRouter);
// app.use('/users', usersRouter);
app.use('/app', userRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;