前端必备
json-server 作用是把一个json文件托管成一个web服务器(提供接口)
有json-server就不用找后端要测试接口啦…
全局安装
npm --install -g json-server
接着随便找或新建个目录
然后准备一个希望返回的json文件,命名为db.json
切换到该目录
启动服务
json-server -w -p 3001 db.json
输出下面内容 说明启动成功!
\{^ - ^}/ hi!
Loading db.json
Done
....
Home
http://localhost:3001
用法
以Ajax为例
GET 获取数据
$.ajax({
url: 'http://localhost:3001/db',
type: 'get',
dataType: 'json',
contentType: 'application/json',
......
})
POST 添加数据
$.ajax({
url: 'http://localhost:3001/db',
type: 'post',
dataType: 'json',
data: JSON.stringify(add),
contentType: 'application/json',
......
})
PATCH 修改数据
$.ajax({
url: 'http://localhost:3001/db/'+id,
type: 'patch',
dataType: 'json',
data: JSON.stringify(add),
contentType: 'application/json',
......
})
DELETE 修改数据
$.ajax({
url: 'http://localhost:3001/db/'+id,
type: 'delete',
dataType: 'json',
contentType: 'application/json',
......
})