-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.roadhogrc.mock.js
More file actions
45 lines (43 loc) · 1.16 KB
/
Copy path.roadhogrc.mock.js
File metadata and controls
45 lines (43 loc) · 1.16 KB
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
var path = require('path');
var fs = require('fs');
var url = require('url')
// 读取本地文件
function fetchFileRespone(res, fileName) {
// console.log(fileName);
const filePath = path.join(__dirname, '/src/mock', fileName);
fs.exists(filePath, function(exists) {
if (exists) {
const data = fs.readFileSync(filePath, 'utf-8');
res.set('Content-Type', 'application/json');
res.end(data);
} else {
res.status('404');
res.end();
}
});
}
// 响应请求
function respone(req, res) {
const urlObj = url.parse(req.url, true);
const fileName = urlObj.pathname;
if (/\.json$/.test(fileName)) {
const filePath = fileName.replace(/^\/api\//, '');
fetchFileRespone(res, filePath);
}
}
export default {
// 本地数据mock
'GET /api/*': function(req, res) {
respone(req, res);
},
// 本地数据mock
'POST /api/*': function(req, res) {
respone(req, res);
},
// 支持值为 Object 和 Array
'GET /test/users': { users: [1,2] },
// GET POST 可省略
'/test/users/1': { id: 1 },
// 支持自定义函数,API 参考 express@4
'POST /test/users/create': (req, res) => { res.end('OK'); },
};