Skip to content

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

Description

@songhlc

前后端分离之本地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都可以进行跳转啦,详细的会在下一篇文章进行介绍

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions