模拟 REST 服务器来伪造在线 API

模拟 REST 服务器来伪造在线 API

原文: https://howtodoinjava.com/angular/mock-rest-server/

学习在本地创建模拟 REST 服务器,该服务器将模拟在线 REST API,并在线生成所需的 JSON 响应。 拥有这样的 REST API 模拟功能非常方便,可以缩短开发时间。

安装 JSON 服务器

在 Node 和 Angular 开发环境中,让我们导入json-server依赖项。

$ npm install -g json-server

//Console Output

C:\Users\admin\AppData\Roaming\npm\json-server -> C:\Users\admin\AppData\Roaming\npm\node_modules\json-server\bin\index.js
+ json-server@0.14.0
added 229 packages from 130 contributors in 24.844s

创建模拟 JSON 响应并提供在线服务

  1. 关于这种方法的最好的事情是,您不会被迫消耗任何意味着更少数据的虚拟对象。 相反,您可以创建要使用的 JSON 数据,并将其放入文件'db.json'中并开始提供它。

    {
      "employees": [
        { "id": 1, "name": "Lokesh", "status": "active" },
        { "id": 2, "name": "Andy", "status": "Inactive" },
        { "id": 3, "name": "Brian", "status": "active" },
        { "id": 4, "name": "Charles", "status": "Inactive" }
      ]
    }
    
    
  2. 并使用简单的命令开始在db.json文件上方投放。

    $ json-server --watch 'E:\ngexamples\db.json'
    
    \{^_^}/ hi!
    
    Loading E:\ngexamples\db.json
    Done
    
    Resources
    http://localhost:3000/employees
    
    Home
    http://localhost:3000
    
    Type s + enter at any time to create a snapshot of the database
    Watching...
    
    
  3. 现在使用命令在浏览器中测试 REST API 'http://localhost:3000/employees'.

    JSON server running

    JSON 服务器运行中

    请注意,由 JSON 服务器提供的 REST 端点由db.json中的数据节点确定。 它是如此简单而强大。

将我的问题放在评论部分。

学习愉快!

参考: json 服务器 github 页面