-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
68 lines (52 loc) · 1.54 KB
/
server.js
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
57
58
59
60
61
62
63
64
65
66
67
const express = require('express');
const path = require('path');
const fs = require('fs');
const Mock = require('mockjs');
const app = express();
const port = 6022;
const apiPath = path.join(__dirname, './api.json');
let apiData = {};
app.listen(port, function () {
console.info('mock server is listening at ' + port)
});
//读取接口配置的JSON文件
let getApi = () => {
let readStream = fs.createReadStream(apiPath, {
encoding: 'utf8'
});
readStream.on('data', (chunk) => {
apiData = JSON.parse(chunk)
});
readStream.on('end', () => {
console.info('读取已完成..');
});
}
fs.watchFile(apiPath, () => {
getApi();
console.info('mock server update');
});
getApi();
app.use((req, res, next) => {
const originalUrl = req.originalUrl;
let data = undefined;
//匹配路径
for (let url in apiData) {
let findItem = apiData[url].find((result) => {
if (result.url === originalUrl) {
return result
}
});
if (findItem !== undefined) {
data = Mock.mock(findItem.res); //使用mock.js创建数据
break;
}
}
// 解决跨域问题
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Authorization,X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method' )
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PATCH, PUT, DELETE')
res.header('Allow', 'GET, POST, PATCH, OPTIONS, PUT, DELETE')
//返回数据
data !== undefined ? res.send(data) : res.sendStatus(404);
next();
});