当前位置: 首页> 财经> 股票 > Vue前端开发必备工具——json-server模拟后端服务器

Vue前端开发必备工具——json-server模拟后端服务器

时间:2025/7/9 21:21:51来源:https://blog.csdn.net/bjzhang75/article/details/141727375 浏览次数:0次

文章目录

  • 1、简介
  • 2、安装
  • 3、快速使用
    • (1)创建JSON文件:
    • (2) 启动json-server
    • (3) 使用API
    • (4) 以其它端口号启动
    • (5) 启动多个API

当我们用Vue开发前端时,如果想调用后端接口,又没有真实的后端接口服务器怎么办?答案是:可以用 json-server

1、简介

  • Json-server 是一个零代码快速搭建本地 RESTful API 的工具。它使用 JSON 文件作为数据源,并提供了一组简单的路由和端点,可以模拟后端服务器的行为。
  • github地址:https://github.com/typicode/json-server
  • npm地址:https://www.npmjs.com/package/json-server

2、安装

  • json-server是基于npm安装的,安装了node就自动安装了npm,所以安装json-server需要先安装node。
  • 安装json-server:使用npm或yarn全局安装json-server。
npm install -g json-server
  • 验证安装是否成功:显示版本号就是安装成功了
json-server -v

3、快速使用

(1)创建JSON文件:

创建一个JSON文件作为数据源,例如 db.json,并在其中定义你想要模拟的数据,例如:

{"users": [{ "id": 1, "name": "John" },{ "id": 2, "name": "Jane" }]
}

(2) 启动json-server

使用以下命令启动json-server,并将JSON文件作为参数传递给服务器。这将在本地计算机的3000端口上启动服务器,并将db.json文件中的数据暴露为RESTful API。

c:\vue3-news>json-server --watch db.json--watch/-w can be omitted, JSON Server 1+ watches for file changes by default
JSON Server started on PORT :3000
Press CTRL-C to stop
Watching db.json...(˶ᵔ ᵕ ᵔ˶)Index:
http://localhost:3000/Static files:
Serving ./public directory if it existsEndpoints:
http://localhost:3000/users

(3) 使用API

可以使用Web浏览器或任何HTTP客户端程序(如Postman)来访问json-server提供的的数据。
例如,以下URL将检索JSON文件中的所有用户:

http://localhost:3000/users

显示:
在这里插入图片描述
并且支持以下的访问方式呦
GET /users
GET /users/:id
POST /users
PUT /users/:id
PATCH /users/:id
DELETE /users/:id

(4) 以其它端口号启动

也可以使用-p参数修改启动的服务器端口号,例如想以8000端口启动json-server,使用以下命令:

json-server --watch db.json -p 8000

(5) 启动多个API

如果想启动多个API,在 json文件中定义多个变量即可。
比如,db.json文件内容:

{"users": [{ "id": 1, "name": "John" },{ "id": 2, "name": "Jane" }],"article":[{"id":1,"article":"Vue3入门到精通"},{"id":2,"article":"JAVA学习"}]}

启动json-server

c:\vue3-news>json-server --watch db.json -p 8000--watch/-w can be omitted, JSON Server 1+ watches for file changes by default
JSON Server started on PORT :8000
Press CTRL-C to stop
Watching db.json...( ˶ˆ ᗜ ˆ˵ )Index:
http://localhost:8000/Static files:
Serving ./public directory if it existsEndpoints:
http://localhost:8000/users
http://localhost:8000/article

这样就启动了http://localhost:8000/usershttp://localhost:8000/article两个接口。
想启动更多API就在json文件中添加就行了。

关键字:Vue前端开发必备工具——json-server模拟后端服务器

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: