React之模拟数据库json-server 2019-01-2
2019-01-26 本文已影响0人
Yokiijay
在前端开发的时候,我们有时候需要验证一些异步请求返回数据后的交互效果,那么就需要搭建一个nodejs服务器来模拟,但是需要自己去在node项目中写比较麻烦,json-server就是快速搭建这样一个node服务器,你只需要创建一个.json的文件,然后监听这个文件就可以了
json-server文档 https://github.com/typicode/json-server
使用json-server
这里我使用yarn本地安装并演示json-server,因为我npm已经有了全局的json-server
终端命令:
cd 你的项目根目录
yarn add json-server
touch data.json
./node_modules/.bin/json-server --watch data.json --port 3004
现在你已经运行了一个小的服务器,通过向http://localhost:3004/myData即可返回数据,但在这之前你需要先在data.json中填写数据
进入data.json
,如下格式
{
"myData": [
{ "name":"小红"},
{ "name":"小黄"},
{ "name":"小张"},
{ "name":"小明"},
{ "name":"小王"}
]
}
打开浏览器,进入http://localhost:3004/myData即可看到json内容,说明能够请求服务器并返回了,终端输入
curl http://localhost:3004/myData
也能看到json内容

