mock.js
- 安裝
# cnpm i mockjs
- 基本使用
const Mock=require('mockjs)
Mock.mock('http://a.com/num', 'post', {
"number|1-100": 100
})
Mock.mock('http://a.com/type',function(options) {
return options.type
}))
現(xiàn)在就可以攔截請求返回 mock 數(shù)據(jù)了,post 請求'http://a.com/num'返回1-100隨機數(shù),請求'http://a.com/type'返回當前請求類型
- 缺點:
- 不及 json-server 使用方便
- 不能跨域使用
- 無法定義復雜結(jié)構(gòu)
具體請看官方文檔
json-server
- 安裝
# cnpm i json-server -g
- 啟動
在項目文件根目錄新建一個 json 文件,例如
{
"data": [{
"name": "張三",
"age": 12,
"id": 0
},
{
"name": "李是",
"age": 22,
"id": 1
},
{
"name": "王五",
"age": 14,
"id": 2
}
]
}
# json-server db.json -p 3001
- 訪問 localhost:3001 就可訪問并操作數(shù)據(jù)了
GET /data 獲取所有數(shù)據(jù)
GET /data/1 獲取id為1的數(shù)據(jù)
DELETE /data/1 刪除id為1的數(shù)據(jù)
POST /data 新增數(shù)據(jù),請求body中必須包含data的屬性數(shù)據(jù)
PUT /data/1 修改數(shù)據(jù),請求body中必須包含data的屬性數(shù)據(jù)
PATCH /data/1 修改數(shù)據(jù),請求body中必須包含data的屬性數(shù)據(jù)
GET /data?age_gte=10 獲取age大于等于10的數(shù)據(jù)
GET /data?_sort=age&_order=asc 根據(jù)age升序排序
更多操作請看官方文檔
graphQL
(這里我們結(jié)合 express 來運行 graphQL)
cnpm install express express-graphql graphql
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
var app = express();
let listData = [{
"name": "張三",
"age": 12,
"id": 0
},
{
"name": "李是",
"age": 22,
"id": 1
}, {
"name": "王五",
"age": 14,
"id": 2
}
]
var schema = buildSchema(`
type Item {
name: String,
age: Int,
id: Int,
}
type Query{
list: [Item]
}
`);
var root = { list: listData };
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));
現(xiàn)在我們在打開的 graphQL 中輸入
query{
list{
id,
name,
age
}
}
就會返回數(shù)據(jù)了, 這里的數(shù)據(jù)是自己寫的假數(shù)據(jù),和 json-server 搭配食用最佳喲
更多操作請看官方文檔
聽說 APIJSON 也不錯官方文檔