Scenes
In the process of the company's React or Vue project development, when the back-end is not ready for the interface, we need to perform data mocks to implement page rendering and simulate front-end and back-end interactions.
We all did this before:
1. Use the local static data json method to simulate the interface data, but in this way we can only read the data, and cannot add, delete, or modify the data.
2. Build a node.js-based server locally, but this requires us to write code to manually build a local server.
3. Install mock.js and simulate the interface to request the data generated by the mock, but the data generated by mock.js is random and may not necessarily make the data we need.
json-server debut
After understanding the shortcomings of several methods of how the front-end simulated interface data for joint debugging in the past, a new data simulation method-JSON-Server.
json-server is a server based on Node.js, which can directly host a json file into a web server with a fully RESTful API, and supports cross-domain, jsonp, routing customization, data snapshot storage and other functions.
JSON-Server official website document: https://github.com/typicode/json-server
This is the first sentence of the official document on json-server:
Get a full fake REST API with zero coding in less than 30 seconds (seriously)
The translation is to build a complete RESTFUL style API service within 30 seconds, 0 code, is this a joke?
From this sentence, we can see the advantages of json-server:
1.0 code quick build
2. Implementation of API service in full compliance with RESTFUL style
Install
npm install -g json-server global installation
Project file creation and data initialization
New db.json
{
"products": [
{
"name": "华为",
"id": 1,
"price": 4000,
"specs": {
"width": 11
}
},
{
"name": "苹果",
"id": 2,
"price": 5000,
"specs": {
"width": 12
}
},
{
"name": "小米",
"id": 3,
"price": 6000,
"specs": {
"width": 13
}
}
]
}
db.json can be understood as a local database. When we access the corresponding add, delete, modify, and check routing interface, the data in
Project configuration
1. Custom configuration
可以在package.json文件中的scripts中进行如下配置:
"json-server": "json-server --watch db.json --port 3006"
2. Then execute the yarn json-server command
3. Now visit http://localhost:3006/products to get all the product data
Base
### get request
/products 请求所有商品
/products/2 请求id为2的商品
/products?name=华为 请求name为华为的商品
### post request
/products
参数params:{
"name": "vivo",
"id": 4,
"price":3600
}
向商品列表中添加一条商品
### put request (update all)
/products/5
params:{
"name": "联想666",
"price":3250
}
将id为5的商品的对象全部替换为{"id":5,"name": "联想666","price":3250}
### patch request (partial update)
/products/4
params:{
price:3200
}
将id为4的商品的price值改为3200 其他的属性值不变
### delete request
/products/1 删除id为1的商品
## Advanced
##### Filter query
/products?name=小米&price_gte=6500 合并查询 name为小米并且price大于6500元的商品
/products?specs.width=13 规格的宽度为13的商品
#### Conditional query _gte is greater than _lte, less than _ne is not equal to _like contains (fuzzy query)
/products?price_gte=4600 价格大于4600的商品
/products?price_lte=8000 价格小于8000的商品
##### Paging query
/products?_page=2&_limit=5 获取第二页的数据 每页请求5条
##### Sort query
/products?_sort=price&_order=desc 根据价格进行排序 排序方式为 desc降序 asc升序
##### Arbitrary slice query
/products?_start=2&_end=4 从索引值为2到索引值为4之间的数据
#### Full-text search query
/products?q=米 查询全部数据中包含”米“关键字的数据
json-server routing configuration
Many times the routing interface we need may not be a simple http://localhost:3000/products format, but
http://localhost:3000/api/products This is where we need to customize the configuration of the routing interface.
Create a new routes.json file and configure as follows
"/api/*": "/$1",
"/:resource/:id/show": "/:resource/:id",
"/posts/:category": "/posts?category=:category",
"/articles\?id=:id": "/posts/:id"
}
Start command configuration
json-server db.json --routes routes.json
Route redirection according to the configuration of the routes.json file:
/api/products # → /products
*** 当访问/api/products路由接口时,服务器会重定向到/products来访问数据,下面的路由配置以此类推***
/api/products/1 # → /products/1
/products/1/show # → /products/1
/products/小米 # → /products?name=小米
/products?id=1 # → /products/1
json-server custom configuration
Custom configuration can be configured in the following two ways
1. Create a new json-server-config.json
Perform command line configuration: json-server --c json-server-config.json db.json In this case, the following configuration will work
{
"port": 5000, //自定义端口
"watch": true, //自动监听变化
"static": "./public", //静态文件路径
"read-only": false, //是否只能使用GET请求
"no-cors": false, //是否支持跨域
"no-gzip": false, //是否支持压缩
"routes": "route.json" //路由配置地址
}
2. json-server command line use
json-server [options] <source>
Options:
--config, -c Path to config file (配置文件)[default: "json-server.json"]
--port, -p Set port (服务器端口) [default: 3000]
--host, -H Set host (host地址) [default:"localhost"]
--watch, -w Watch file(s) (监听json文件) [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(是否只支持get请求) [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]
Command line execution:
1. The source can be a json file or a js file
2. Command line configuration examples
json-server -c xxx.config.json --routes routes.json -p 8001 -i pid .... db.json
Chrome plug-in web front-end assistant FeHelper tool
When we request /products on the browser, we get the json data in db.json
After installing FeHelper, our data is automatically formatted on the browser, and the json data can also be folded, sorted, and downloaded. Does the json data we display become more beautiful? ! !
chrome浏览器安装流程:
1. https://github.com/zxlie/FeHelper/tree/master/apps/static/screenshot/crx
从github上下载最新版本的crx文件
2.chrome浏览器地址栏输入:chrome://extensions/ 并打开
3.右上角开启开发者模式
4.拖拽crx到当前页面,完成安装
After understanding the basic use of json-server, we can use json when we build our own local React or Vue projects
-server builds a local server to add, delete, modify and check the data in the database db.json, so there is no need to worry about the data loss after refreshing the page.
Next, let us use json-server in actual projects! ! !
The author's understanding of json-server belongs to the basic entry level. For the understanding or use errors in the article, I hope you will not hesitate to point out that you can comment on json-server that needs to be added. The author is very grateful. Typesetting codewords is not easy. If it is helpful to you, please give me a thumbs-up!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。