Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

利用json-server搭建本地mock-server #16

Open
songhlc opened this issue Aug 7, 2016 · 0 comments
Open

利用json-server搭建本地mock-server #16

songhlc opened this issue Aug 7, 2016 · 0 comments

Comments

@songhlc
Copy link
Owner

songhlc commented Aug 7, 2016

前后端分离之本地mock-server

前后端分离之后,前端不依赖于后端服务的进度,在前后端定义好json接口之后,就可以开始开发了。

基于json-server我们可以很方便的定义好本地调用的restful服务,然后在前端通过proxy,修改服务调用即可。

json-server:Github地址

  • 安装json-server
$ npm install -g json-server
  • 简单的例子:
  1. 在目录下创建一个 db.json
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
  1. 运行json-server
$ json-server --watch db.json

默认json-server会启动本地3000端口。
通过访问http://localhost:3000/posts/1, 会返回以下数据

{ "id": 1, "title": "json-server", "author": "typicode" }
  1. 使用routes

以当前项目例子,实际后台服务访问路径为

http://localhost/yuncai/qutate/loaddata

然后json-server 初步使用发现json-server好像不支持超过三层路径的访问

{
  "qutate/getdata": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "yuncai/qutate/loaddata": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

通过以上定义的db.json

通过下面的url,可以正常返回数据。

http://localhost:3000/qutate/getdata

但通过下面的url则返回结果为{}

http://localhost:3000/yuncai/qutate/loaddata

还没有深入研究详细原因,目前暂时通过配置routes.json的方式来解决。

1. 在本地创建routes.json
2. 启动参数改成 json-server db.json --watch --routes routes.json
3. 访问http://localhost:3000/yuncai/qutate/loaddata 成功返回数据
  1. get请求里带请求的访问
http://localhost:3000/qutate/getdata/1 //返回id 为1 的数据

http://localhost:3000/qutate/getdata?title=json-server //返回title字段等于json-server的数据

以上就能用最简单的方式搭建起本地的mock-server 进行前后端分离的调试啦。
本地可以使用proxy或者nginx都可以进行跳转啦,详细的会在下一篇文章进行介绍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant