首页

  • 首页
  • 友链
  • 标签
  • 关于

“node路由模块化”

白羊座的梦 发布于 2020-01-29

node app获取路由配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
	const express = require("express");
const fs = require("fs");
const path =require("path");

const app = express();

// 可以通过require导出
// const User = require("./mock/user");
// const home = require("./mock/home");

//也可以通过读取模块
// 获取mock路径
const mockPath = path.join(__dirname,"mock");
//存放mock数据的
let mockDate = {};
// console.log(mockPath);
//读取文件夹
// fs.readdir(mockPath,(err,filename)=>{
// console.log(filename);
// })
const filename = fs.readdirSync(mockPath);
// console.log(filename);

filename.forEach(item => {
//拿到对象的内容
console.log(require(path.join(mockPath,item)));
//通过对象合并,把数据合并到一个对象中来
Object.assign(mockDate,require(path.join(mockPath,item)));
//这个是错误的写法;
// mockDate.assign(require(path.join(mockPath,item)));

});
// console.log(mockDate);

//设置接口
for(let key in mockDate){
// console.log(key,mockDate[key]);
let [method,url] = key.split(" ");
method = method.toLowerCase();
// console.log(method,url,mockDate[key]);
//把格式化数据放到app接口中;
app[method](url,mockDate[key]);
}
//注意:这种方式比require好在如果添加了文件就不需要导入了。直接就可以读取所有;

// 接口
app.get("/",(req,res)=>{
console.log("5000监听完毕");
res.send("成功")
})

//监听端口
const prot = 5000
app.listen(prot,(err)=>{
console.log(`端口${prot}监听完毕`);
})

node路由配置文件

1
2
3
4
5
6
7
8
9
10
11
12
//暴露出一个路由配置对象;
module.exports = {
"GET /home":function(req,res){
console.log("/home");
res.send("/home")
},
"GET /home/search":function(req,res){
console.log("/home/search");
res.send("/home/search")

}
}
Newer
函数节流和防抖封装
Older
高阶组件

© 2020 白羊座的梦

Powered by Hexo Theme - flex-block