express 的路由分离
在做大型项目是一般不会把路由写入server.js里,所以就有了路由分离
1.在项目目录下创建router文件夹
user.js
var express = require("express"); var router = express.Router(); var userRouter = router.get("/user", function(req,res) { res.send('user') }); module.exports = userRouter
root.js
var express = require("express"); var router = express.Router(); var rootRouter = router.get("/", function(req,res) { console.log('get') res.send('Root') }); module.exports =rootRouter
server.js
var express = require('express'); var userRouter = require('./router/user') var rootRouter = require('./router/root') var app = express(); //路由分离 app.use('/',rootRouter) app.use('/',userRouter) app.listen(8001) console.log('listening to port 8001');