郭卫东 发表于 2024-11-1 09:26:40

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

当我们用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 exists

Endpoints:
http://localhost:3000/users


(3) 使用API

可以使用Web欣赏器或任何HTTP客户端程序(如Postman)来访问json-server提供的的数据。
比方,以下URL将检索JSON文件中的所有用户:
http://localhost:3000/users
显示:
https://i-blog.csdnimg.cn/direct/09ea13fe4d634da3b3fe335bcc8b8d23.png#pic_center
并且支持以下的访问方式呦
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 defaultJSON Server started on PORT :8000Press CTRL-C to stopWatching db.json...( ˶ˆ ᗜ ˆ˵ )Index:http://localhost:8000/Static files:Serving ./public directory if it existsEndpoints:http://localhost:8000/usershttp://localhost:8000/article 如许就启动了http://localhost:8000/users和http://localhost:8000/article两个接口。
想启动更多API就在json文件中添加就行了。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Vue前端开发必备工具——json-server模仿后端服务器