作为一个前端开发工程师,在后端还没有ready的时候,不可避免的要使用mock的数据。很多时候,我们并不想使用简单的静
态数据,而是希望自己起一个本地的mock-server来完全模拟请求以及请求回来的过程。json-server是一个很好的可以替我们完
成这一工作的工具。我们只需要提供一个json文件,或者写几行简单的js脚本就可以模拟出RESTful API的接口。
官方文档: https://github.com/typicode/json-server
1.使用
1.安装
npm install -g json-server
2.创建 db.json
{
"users":[
{
"name" : "张三",
"age":30,
"score":89
},
{
"name":"李四",
"age":43,
"score":89
},
{
"name":"王五",
"age":34,
"score":89
}
]
}
3.启动服务
例如以下命令,把db.json文件托管成一个 web 服务。
$ json-server --watch --port 53000 db.json
输出类似以下内容,说明启动成功。
> json-server --watch --port 8900 db.json
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:8900/users
Home
http://localhost:8900
Type s + enter at any time to create a snapshot of the database
Watching...
GET /users 200 13.595 ms - 188
我们用浏览器访问 : http://localhost:8900/users

也可以使用js文件 代替json文件
// index.js
module.exports = () => {
const data = { users: [] }
// Create 1000 users
for (let i = 0; i < 1000; i++) {
data.users.push({ id: i, name: `user${i}` })
}
return data
}
$ json-server index.js
2. 路由
创建一个路由json ,routes.js
{
"/api/*": "/$1",
"/:resource/:id/show": "/:resource/:id",
"/posts/:category": "/posts?category=:category",
"/articles\\?id=:id": "/posts/:id"
}
db.json
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}
使用 --routes 选项进行启动
json-server db.json --routes routes.json
> json-server db.json --routes routes.json
\{^_^}/ hi!
Loading db.json
Oops, db.json doesn't seem to exist
Creating db.json with some default data
Loading routes.json
Done
Resources
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
Other routes
/api/* -> /$1
/:resource/:id/show -> /:resource/:id
/posts/:category -> /posts?category=:category
/articles\?id=:id -> /posts/:id
Home
http://localhost:3000
我们可以访问以下路由:
http://localhost:3000/api/posts
http://localhost:3000/api/posts/1
http://localhost:3000/posts/1/show
其他路由:
3.条件查询
GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode
分页
使用_page(第几页) 和 _limit(每页多少条) 去分页
GET /posts?_page=7
GET /posts?_page=7&_limit=20
默认每页10条
排序
使用_sort 和 _order 关键字去排序
GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc
多个字段进行排序
GET /posts?_sort=user,views&_order=desc,asc
其他操作
- _gte 大于等于
- _lte 小于等于
GET /posts?views_gte=10&views_lte=20
- _ne 不等于
GET /posts?id_ne=1
- _like 包含
GET /posts?title_like=server
- q 全文检索
GET /posts?q=internet
4. --middlewares参数
// hello.js
module.exports = (req, res, next) => {
res.header('X-Hello', 'World')
next()
}
上面代码是 给响应头添加自定义字段:

5. json-server 的相关启动参数
语法: json-server [options]
| 参数 | 简写 | 说明 | 默认值 |
|---|---|---|---|
| –config | -c | 配置文件路径 | [默认值: “json-server.json”] |
| –port | -p | 设置端口 | [默认值: 3000] |
| –host | -H | 设置域名 | [默认: “localhost”] |
| –watch | -w | 监控文件 | [true] |
| –routes | -r | 路由文件 | |
| –middlewares | -m | 中间文件 | [array] |
| –static | -s | Set static files directory | |
| –read-only | –ro | Allow only GET requests | [boolean] |
| –no-cors | –nc | Disable Cross-Origin Resource Sharing | [boolean] |
| –no-gzip | –ng | Disable GZIP Content-Encoding | [boolean] |
| –snapshots | -S | Set snapshots directory | [default: “.”] |
| –delay | -d | Add delay to responses | |
| –id | -i | Set database id property (e.g. _id) | [default: “id”] |
| –foreignKeySuffix | –fks | Set foreign key suffix, (e.g. _id as in post_id) | [default: “Id”] |
| –quiet | -q | Suppress log messages from output | [boolean] |
| –help | -h | Show help | [boolean] |
| –version | -v | Show version number | [boolean] |
实例:
文件可以是JSON 或者jS 文件
json-server db.json
json-server file.js
json-server http://example.com/db.json
6.高级用法
我们可以使用编程,来实现高级用法
1.自定义路由
当你路由的时候,如果是POST方式,则需要在body带上当前时间,实现代码如下:
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.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')
})
资源授权例子
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use((req, res, next) => {
if (isAuthorized(req)) { // add your authorization logic here
next() // continue to JSON Server router
} else {
res.sendStatus(401)
}
})
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
自定义输出内容
// In this example, returned resources will be wrapped in a body property
router.render = (req, res) => {
res.jsonp({
body: res.locals.data
})
}
你可以定义自己的响应code
// In this example we simulate a server side error response
router.render = (req, res) => {
res.status(500).jsonp({
error: "error message here"
})
}
本文介绍了如何通过json-server快速创建本地mock服务器,演示了如何配置静态数据、路由、条件查询、分页、排序以及高级定制功能,如自定义路由和输出。适合前端和后端开发者在API未就绪时进行开发测试。
1423

被折叠的 条评论
为什么被折叠?



