Skip to content

前后端分离之后前端如何快速Mock数据 #2

Description

@webplus

JSON-SERVER官方是这样描述的:零编程,3秒构建REST API测试接口

第一步:安装

$ npm install -g json-server

第二步:创建数据文件

Create a db.json file:

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

第三步启动数据服务

启动服务之前先创建好接接口返回的数据结构
$ json-server --watch db.json --port 3000

使用数据

访问接口:http://localhost:3000/posts/1

{ "id": 1, "title": "json-server", "author": "typicode" }

API

GET /posts
GET /posts/1
GET /posts/1/comments
GET /comments?postId=1
GET /posts?userId=1
POST/posts
PUT /posts/1
PATCH   /posts/1
DELETE  /posts/1

静态文件服务

  • 创建一个static目录
  • 启动服务:
json-server db.json --static ./static

与Webpack接合

$ npm install --save-dev http-proxy-middleware
proxy: {
  '/some/path*': {
    target: 'https://other-server.example.com',
    rewrite: function(req) {
       req.url = req.url.replace(/^\/api/, '');
    },
    secure: false
  }
}

关于Webpack-dev-server的相关信息参考webpack-dev-server
这样本地开发服务器与后台接口服务器通过这样代理后就能使用同一服务器,很好的避免多环境下接口适应的问题,规避了跨域的情况

json-server

jsonplaceholder

webpack-dev-server

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions