Json-server + mockjs模拟假数据

鉴于这个代码开源出去感觉会被打,还是写个博客吧。

其实操作很简单,只要把文件读取,通过mock转化,再导出文件,然后在json-server填写相应路径即可。

源文件test.json

1
2
3
4
5
6
7
8
9
{
"list|1-10": [{
"id|+1": 1
}],
"user": {
"name": "@name",
"id": "@id"
}
}

通过mockjs处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const Mock = require('mockjs');
const fs = require("fs");

let data = fs.readFileSync("test.json", "utf-8");

data = data.toString();
data = JSON.parse(data)
data = Mock.mock(data);
data = JSON.stringify(data);

fs.writeFile('res.json', data, function(err){
if(err){
console.error(err);
}
})

{"list":[{"id":1},{"id":2},{"id":3}],"user":{"name":"John Martinez","id":"320000199809111043"}}

完整json-server配置文件

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

// server.js
const path = require('path');
const fs = require("fs");
const Mock = require('mockjs');
const jsonServer = require('json-server')

let data = fs.readFileSync("test.json", "utf-8");

data = data.toString();
data = JSON.parse(data)
data = Mock.mock(data);
data = JSON.stringify(data);

fs.writeFile('res.json', data, function(err) {
if(err){
console.error(err);
}
const server = jsonServer.create()
const router = jsonServer.router(path.join(__dirname, 'res.json'))
const middlewares = jsonServer.defaults()

// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)

// Add custom routes before JSON Server router
server.get('/echo', (req, res) => {
res.jsonp(req.query)
})

// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
// Continue to JSON Server router
next()
})

// Use default router
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})

})

打开localhost:3000

富婆,饭饭