安装json-server
-
npm install -g json-server
image.png
- 创建json文件
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
- 启动
json-server db.json
E:\Study\模板式表单>json-server db.json
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
Home
http://localhost:3000
为了方便,再创建一个 package.json 文件,写入
{
"scripts": {
"mock": "json-server db.json --port 3003"
}
}
操作数据
- get获取 post 添加 put 修改 delete删除 patch 是对put的补充部分更新
mockJs的使用
下面是一个使用 mockjs 构造的比较复杂的数据格式,对象是一个新闻列表,其中有100条新闻,每条新闻有对应的id,标题,内容,简介,标签,浏览量,和一个图片数组:
# /mock/db.js
let Mock = require('mockjs');
let Random = Mock.Random;
module.exports = function() {
var data = {
news: []
};
var images = [1,2,3].map(x=>Random.image('200x100', Random.color(), Random.word(2,6)));
for (var i = 0; i < 100; i++) {
var content = Random.cparagraph(0,10);
data.news.push({
id: i,
title: Random.cword(8,20),
desc: content.substr(0,40),
tag: Random.cword(2,6),
views: Random.integer(100,5000),
images: images.slice(0,Random.integer(1,3))
})
}
return data
}
/mock 下运行
json-server db.js -p 3003
vscode插件rest-client中,对json-server实现增删改查操作
### posts
@contentType = application/json
### get
GET http://localhost:3001/posts
### post
POST http://localhost:3001/posts
Content-Type: {{contentType}}
{
"id": 5,
"title": "json-server",
"author": "typicode222"
}
### put
PUT http://localhost:3001/posts/2
Content-Type: {{contentType}}
{
"title": "json-44",
"author": "typicode33"
}
### delete
DELETE http://localhost:3001/posts/1
### comments
### get
GET http://localhost:3001/comments
### post
POST http://localhost:3001/comments
### put
PUT http://localhost:3001/comments
### delete
DELETE http://localhost:3001/comments
### profile
### get
GET http://localhost:3001/profile
### post
POST http://localhost:3001/profile
content-type: application/json
{
"id": 2,
"body": "some comment",
"postId": 1
}
### put
PUT http://localhost:3001/profile/2
### delete
DELETE http://localhost:3001/profile
------------------------
data.json
------------------------
{
"posts": [
{
"title": "json-44",
"author": "typicode33",
"id": 2
},
{
"id": 3,
"title": "json-server",
"author": "typicode222"
},
{
"id": 1,
"title": "json-server",
"author": "typicode222"
},
{
"id": 5,
"title": "json-server",
"author": "typicode222"
}
],
"comments": [],
"profile": {
"id": 2,
"body": "some comment",
"postId": 1
}
}
网友评论