当前位置: 首页 > Web前端 > HTML5

json-server的关系图(Relationships)

时间:2023-04-05 17:07:03 HTML5

json-server的关系图json-server是一个非常好用的模拟RESTAPI的工具,文档也非常详细和全面。详情:json-server和关系图是一个非常强大的功能,可以轻松实现多路由之间关联数据的获取。样本数据官网上关系图的案例很好。我将在其示例的基础上对其进行改进和解释。首先,我在这里写了一个原始数据,db.json:{"posts":[{"id":1,"title":"帖子的第一个标题","author":"typicode"},{"id":2,"title":"帖子的第二个标题","author":"tangcaiye"}],"comments":[{"id":1,"body":"somecomment1111","postId":2},{"id":2,"body":"somecomment2222","postId":1}],"profile":{"name":"typicode"}}这是对这个db.json的数据内容:这个json文件中的posts和comments是相关联的,它们之间的关系是通过comments下的postId属性,postId对应posts的id。比如comments下的postId:2对象关联posts下的{"id":2,"title":"帖子第二个标题","author":"tangcaiye"},_embed在_embedjson-server用于获取包含下层资源的数据。比如我的json-server服务器的端口号是8081,那么我的请求路径是http://localhost:8081/posts/2?_embed=comments这个路径是在posts下获取id为2的数据及其关联的commentsdata:{"id":1,"body":"somecomment1111","postId":2}输出结果为:{"id":2,"title":"post'ssecondtitle","author":"tangcaiye","comments":[{"id":1,"body":"somecomment1111","postId":2}]}_expand如果懂了_embed,那么_expand就很容易了。_expand获取包含上级资源的数据:路径:http://localhost:8081/comments/2?_expand=post以上路径获取到评论下id为2的数据及其关联的上级资源post,即,underposts:{"id":1,"title":"帖子的第一个标题","author":"typicode"}outputresult:{"id":2,"body":"somecomment2222","postId":1,"post":{"id":1,"title":"文章首标题","author":"typicode"}}只获取下层资源有时候我们可能想只获取下级资源,可以通过:路径:http://localhost:8081/posts/2/comments以上路径是获取posts的id:2关联的评论数据:返回结果:[{“身份证”:1,“身体”:“一些评论1111”,“postId”:2}]

最新推荐
猜你喜欢