Get a full fake REST API with zero coding in less than 30 seconds (seriously)
Created with <3 for front-end developers who need a quick back-end for prototyping and mocking.
See also:
* :dog: husky - Git hooks made easy
* :hotel: hotel - developer tool with local .dev domain and https out of the box
* :atom_symbol: react-fake-props - generate fake props for your React tests (Jest, Enzyme, …)
* :heart: Patreon page - if you want to support JSON Server development
JSON服务器和我的其他项目的开发得到了人们的慷慨支持。如果你从我的项目中受益,并且愿意帮助他们保持经济上的可持续发展, 请访问 Patreon.
如果你是一家公司,你可以在这里有你的标志。
创建一个 db.json
文件
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
开启 JSON 服务器
$ json-server --watch db.json
现在如果你移步到 http://localhost:3000/posts/1, 你将得到:
{ "id": 1, "title": "json-server", "author": "typicode" }
在做请求的时候,你还应该知道:
如果你进行POST,PUT,PATCH或者DELETE请求,所做的改变将使用 lowdb自动和安全地存在到db.json
中。
你的请求主体应该是包含对象的, 就像 GET 请求输出的一样. (如 {"name": "Foobar"}
)
id值是不可变的. 任何 id
值 在你的PUT或者PATCH请求主体中都是被忽略的。只有在POST请求中的值才会被重视,但前提是它还不存在。
一个 POST, PUT 或者 PATCH 请求应该在请求主体中包含 一个 Content-Type: application/json
头部来使用JSON数据。否则它将产生200 OK
的结果,但数据并不会更新。
$ npm install -g json-server
基于前面的 db.json
文件, 这里是所有的迷人路由. 你也可以使用 --routes
添加 其他路由
GET /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
GET /profile
POST /profile
PUT /profile
PATCH /profile
使用 .
来访问深层的属性
GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode
使用 _page
和可选的 _limit
来使返回的数据进行分页。
在 Link
头部中,你将获得一个 first
, prev
, next
和 last
连接.
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
添加 _start
和 _end
或者 _limit
(一个 X-Total-Count
头部 是被包含在响应中的)
GET /posts?_start=20&_end=30
GET /posts/1/comments?_start=20&_end=30
GET /posts/1/comments?_start=20&_limit=10
工作原理和 Array.slice完全一样 (这是一个前闭后开区间[star, end)
)
添加 _gte
或者 _lte
来获取一个范围
GET /posts?views_gte=10&views_lte=20
添加 _ne
来排除一个值
GET /posts?id_ne=1
添加 _like
来过滤 (支持RegExg)
GET /posts?title_like=server
添加 q
GET /posts?q=internet
包含子资源, 添加 _embed
GET /posts?_embed=comments
GET /posts/1?_embed=comments
包含父资源, 添加 _expand
GET /comments?_expand=post
GET /comments/1?_expand=post
获取或者创建嵌套的资源(默认为一层, 添加自定义路由来获得更多层级)
GET /posts/1/comments
POST /posts/1/comments
GET /db
Returns default index file or serves ./public
directory
返回默认的索引文件或者服务./public
目录。
GET /
你可以使用JSON服务器来服务你的HTML,JS和CSS,简单的创建一个./public
目录或者使用--static
来设置不同的静态文件目录。
mkdir public
echo 'hello world' > public/index.html
json-server db.json
json-server db.json --static ./some-other-dir
你可以使用--port
标记在其他端口上开启JSON服务器
$ json-server --watch db.json --port 3004
你可以从任何地方使用CORS 和 JSONP访问你的fake API 。
你可以加载远程模式.
$ json-server http://example.com/file.json
$ json-server http://jsonplaceholder.typicode.com/db
使用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
Tip 使用模块 诸如: Faker, Casual, Chance or JSON Schema Faker.
中文开发的话,推荐使用Mock
在开发中有很多方法可以设置SSL。一个简单的方法就是使用hotel。 hotel.
创建一个routes.json
文件。注意,每一条路径都应该以/
开头。
{
"/api/*": "/$1",
"/:resource/:id/show": "/:resource/:id",
"/posts/:category": "/posts?category=:category",
"/articles\\?id=:id": "/posts/:id"
}
使用 --routes
选项开启 JSON 服务器 .
json-server db.json --routes routes.json
现在你可以使用其他路由访问资源
/api/posts # → /posts
/api/posts/1 # → /posts/1
/posts/1/show # → /posts/1
/posts/javascript # → /posts?category=javascript
/articles?id=1 # → /posts/1
你可以在命令行借口使用middlewares
选项添加中间件:
// hello.js
module.exports = (req, res, next) => {
res.header('X-Hello', 'World')
next()
}
json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js
json-server [options]
Options:
--config, -c Path to config file [default: "json-server.json"]
--port, -p Set port [default: 3000]
--host, -H Set host [default: "0.0.0.0"]
--watch, -w Watch file(s) [boolean]
--routes, -r Path to routes file
--middlewares, -m Paths to middleware files [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 (ms)
--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]
Examples:
json-server db.json
json-server file.js
json-server http://example.com/db.json
https://github.com/typicode/json-server
你还可以在一个叫json-server.json
配置文件中设置选项。
{
"port": 3000
}
如果您需要添加身份验证、验证或任何行为,您可以将该项目作为模块与其他Express中间件结合使用。
$ npm install json-server --save-dev
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
$ node server.js
你提供给jsonServer.router
函数的路径是相对于你启动你的node进程的目录的。如果你想从另外的目录运行上面的代码,最好使用绝对路径:
const path = require('path')
const router = jsonServer.router(path.join(__dirname, 'db.json'))
对于内存中的数据库,只需要将一个对象传递给jsonServer.router()
.
注: jsonServer.router()
可用于现有的Express 项目.
假设你想要一条响应查询参数的路由,和一条在创建的每一个资源上设置时间戳的路由。
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
// 设置默认的中间件 (logger, static, cors and no-cache)
server.use(middlewares)
//在JSON Server router之前添加自定义路由
server.get('/echo', (req, res) => {
res.jsonp(req.query)
})
//你需要使用一个body-parser来处理POST,PUT和PATCH
//你可以使用JSON Server使用的那个
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
// 继续json-server路由
next()
})
// 使用默认路由
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)) { // 在这儿添加你的权限逻辑
next() // 继续json-server路由
} else {
res.sendStatus(401)
}
})
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
想要修改响应, 需要重写 router.render
方法:
// 在这个例子中,返回的资源将被包裹在一个body属性中
router.render = (req, res) => {
res.jsonp({
body: res.locals.data
})
}
你可以给响应设置自己的状态码
// 在这个例子中,我们模仿了服务器端错误响应
router.render = (req, res) => {
res.status(500).jsonp({
error: "error message here"
})
}
使用 jsonServer.rewriter()
改写写路由规则
// 路由规则要在 server.use(router)之前添加
server.use(jsonServer.rewriter({
'/api/*': '/$1',
'/blog/:resource/:id/show': '/:resource/:id'
}))
或者,您也可以在/api
上安装路由器
server.use('/api', router)
jsonServer.create()
返回一个 Express 服务器.
jsonServer.defaults([options])
返回JSON服务器使用的中间件
static
静态文件路径logger
启用 logger 中间件 (默认值: true)bodyParser
启用 body-parser 中间件 (默认值: true)noCors
禁用 CORS (默认值: false)readOnly
只接受 GET 请求 (默认值: false)jsonServer.router([path|object])
返回一个JSON 服务器路由
你可以部署 JSON 服务器. 例如, JSONPlaceholder 是一个由JSON服务器驱动的在线假API,并在Heroku上运行。
MIT - Typicode - Patreon