1. 原始index.js文件内容如下

可以运行以上代码,在浏览器中输入localhost:3000/users/zhangyanming, 试试看效果
express 使用了 path-to-regexp 模块实现的路由匹配
参数解析简单介绍:
req.query: 解析后的 url 中的 querystring,如 ?name=zhym,req.query 为 {name: ’zhym‘}
req.params: 解析 url 中的占位符,如 /:name,访问 /’zhym,req.params 的值为 {name: ’zhym'}
req.body: 解析后请求体,需使用相关的模块,如 body-parser,请求体为 {"name": ’zhym'},则 req.body 为 {name: ’zhym'}
2. 应用Express Router
(1)在project目录下新建routes文件夹,新建index.js 和 users.js
(2)编写users.js路由文件

(3)编写index.js路由文件

(4)改写index.js主程序

更多Router用法,详见官方文档
网友评论