前言
基于上一篇Web Api Controller分类,在MVC中我们通常要按自己的业务来划分Controller层, 好处多多,那么Express框架作为Node.js的一款MVC框架,那么自然也会想到这个问题。 用express框架创建的项目默认是直接在routes和views文件夹下放直接的路由和页面文件。 这篇文章里我就分享下在Express里给路由文件和页面分类。
项目结构图
在该项目中,我依然按照二级目录和三级目录的方式来划分业务逻辑,和上篇WebApi保持相同。routes下分为ContractUs和Products两个文件夹。views里我只放了ContractUs相关文件夹,其余可自己创建试试。
实现思路
1、在Express里主要是依靠app.js来实现路由导航,关键点就是在require和use这两个方法上。 require()则直接传一个相对路径一直到你的路由文件上,use()是路径导航,你可以根据业务划分的文件夹规则来定义。
//系统默认路由 var routes = require('./routes/index'); var users = require('./routes/users'); //自定义分类 var advise = require('./routes/ContractUs/Advise'); var product = require('./routes/ContractUs/Product'); app.use('/', routes); app.use('/users', users); app.use('/ContractUs/Advise', advise); app.use('/ContractUs/Product', product);
2、根据use里的路径测试一下分类后的效果
① 默认请求 http://localhost:3000/
②http://localhost:3000/ContractUs/Advise 返回页面
③http://localhost:3000/ContractUs/Advise/list 返回页面
④http://localhost:3000/ContractUs/Product 返回字符串
总结
直接下载demo试试。