json-server快速“伪造”后台接口

来源:互联网 发布:飞利浦呼吸机读卡软件 编辑:程序博客网 时间:2024/04/30 23:47

环境
需要安装 node https://nodejs.org/en/

开始
1.新建项目 mkdir rest-api-demo && cd rest-api-demo

2.初始化项目 npm init

3.安装 npm install --save-dev json-server

4.在项目根目录下,新建一个 JSON 文件db.json

{  "posts": [    { "id": 1, "title": "json-server", "author": "typicode" }  ],  "comments": [    { "id": 1, "body": "some comment", "postId": 1 }  ],  "profile": { "name": "typicode" }}

5.打开 package.json,在 scripts 字段添加一行

"scripts": {  "server": "json-server db.json", // 新加行  "test": "..."}

6.启动服务 npm run server

\{^_^}/ hi!Loading db.jsonDoneResourceshttp://localhost:3000/postshttp://localhost:3000/commentshttp://localhost:3000/profile

三个接口已经生成,支持post(新增) delete(删除) put(修改) get(查询);
推荐使用 postman 进行测试

自定义路由
1.创建一个JSON文件 routes.json
必须以/开始

{  "/api/": "/",  "/blog/:resource/:id/show": "/:resource/:id",  "/blog/:category": "/posts/:id?category=:category"}

2.修改启动参数 package.json

"scripts": {  "server": "json-server db.json --routes routes.json", // 修改行  "test": "..."}

3.启动服务 npm run server

\{^_^}/ hi!Loading db.jsonLoading routes.jsonDoneResourceshttp://localhost:3000/postshttp://localhost:3000/commentshttp://localhost:3000/profileOther routes/api/ -> //blog/:resource/:id/show -> /:resource/:id/blog/:category -> /posts/:id?category=:category

参考代码:JavaScript-study/rest-api-demo

详情查看:https://www.npmjs.com/package/json-server

0 0