这里介绍一款非常好用的 json-server 数据模拟服务器。用来生成数据接口,以便前端开发者的数据模拟。
-
全局安装 json-server
$ npm install -g json-server
-
创建一个 json 文件,假设文件名为
data.json
{ "user": [ {"id": 1, "username": "张三", "password": "abc123"}, {"id": 2, "username": "李四", "password": "abc456"} ], "list": [ {"id": 1, "title": "商品1", "content": "12345"}, {"id": 2, "title": "商品2", "content": "abcde"} ] }
-
在文件所在目录打来终端,运行服务器
$ json-server --watch data.json # or 指定端口号 $ json-server --watch data.json --port 5000
-
服务器运行成功后,会根据 json 文件,生成对应 RestFul 接口;这里会生成两个接口
// 接口一: http://localhost:5000/user // 接口二: http://localhost:5000/list
RestFul 接口:指的是对同一个接口地址,可以进行 get、post、put、delete 四种方式的请求,从而达到对数据的增删改查操作。
// get 请求 获取数据 axios.get('http://localhost:5000/user').then(res => { console.log(res) }) // post 请求 提交数据 axios.post('http://localhost:5000/user', { username: '王五', password: 'abc789' }).then(res => { console.log(res) }) // put 请求 更新数据 axios.put('http://localhost:5000/user/1', { username: '张三' password: '123456' }).then(res => { console.log(res) }) // delete 请求 删除数据 axios.delete('http://localhost:5000/user/1').then(res => { console.log(res) })