使用json-server 模拟后端数据

1. json-server是什么

json-server 是一个 Node 模块,运行 Express 服务器,你可以指定一个 json 文件作为 api 的数据源。 简单的说,它可以模拟小型后台接口,在一个JSON文件中操作数据,是基于的node.js的一个模块。

比如在学习axios时候,就可以用json-server来模拟接口。

2.安装和使用

全局安装(在node环境下)

npm install -g json-server

创建一个名为db.json文件,并且存放好以下数据

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

文件中的数据是可以修改的,但是对象名最好不要改(posts、comments、profile)。

启动服务

注意:启动服务必须在db.json文件目录下

json-server --watch db.json

这样就是成功了,可以ctrl+链接查看数据
在这里插入图片描述接下来就可以使用默认的接口了。

GET /posts 得到posts中的数据
GET /posts/1 得到posts中id为1的数据
POST /posts 传输数据给posts
PUT /posts/1 增加资源给posts
PATCH /posts/1 通过query方式传参
DELETE /posts/1 删除数据

也可以自定义路由器和排序等其他用法,这里不过多介绍,官网里写的很详细。

3.通过axios测试

//测试GET
axios.get("http://localhost:3000/posts").then((result) => {
             console.log(result);
         }).catch((err) => {
             console.warn(err);
         }).then(function () {
             // 总是会执行
         });;

成功发送请求

在这里插入图片描述

//测试POST
axios.post('http://localhost:3000/posts', {
            title: "POST请求",
            author: "小M."
        }).then((result) => {
            console.log(result);
        }).catch((err) => {
            console.log(err);
        });

在这里插入图片描述其他接口的用法都是大同小异的。

无法加载json-server.ps1问题解决

无法加载文件xx\npm\json-server.ps1,因为在此系统上禁止运行脚本。

查了些资料发现是PowerShell执行脚本的安全策略出了问题。

  • Restricted: 禁止运行任何脚本和配置文件。(默认)
  • 如图输入PowerShell(PowerShell就是更强大的cmd)。
  • RemoteSigned :可以运行脚本,但要求从网络上下载的脚本和配置文件由可信发布者签名;不要求对已经运行和已在本地计算机编写的脚本进行数字签名。
  • Unrestricted :可以运行未签名脚本。(危险!)

解决方案:

  1. win+R打开这个框。
  2. 如图输入PowerShell(PowerShell就是更强大的cmd)。

在这里插入图片描述
3. 输入

Get-ExecutionPolicy

一般情况会是默认的 Restricted ,接下来把它改成RemoteSigned就可以了。

Set-ExecutionPolicy RemoteSigned 输入y确认

在这里插入图片描述
再重新启动

json-server --watch db.json

链接:https://juejin.cn/post/7088666061339361293
来源:稀土掘金

猜你喜欢

转载自blog.csdn.net/Quentin0823/article/details/131655081