给前端开发人员的Mock Server(前端codereview)

说明

前端开发人员在工作学习中,除了页面布局,样式调整,各种组件的调用外,很重要的也是很基础的工作就是调用服务端接口。

但是在很多时候,接口是没有的。例如个人学习时,没有接口——除非前端开发人员自己用NodeJS、Go、Python、Java写一个服务端,但这也是有点难度;亦或工作中,服务端开发人员只给了接口文档,对应的接口还不具备联调的条件。

那么自己搞一个简单的,具备基本功能的,有Mock数据的服务端就很有必要了。

本文简单介绍一下几个,两个网络,一个本地。

相关网址就不放了,大家关键字搜一下就行了。

JSONPlaceholder

这是一个免费的在线REST API,带了6组常见的资源:100个帖子(posts)、500条评论(comments)、100张专辑(albums)、5000张照片(photos)、200个待办事项((todos)、10个用户(users)。

这里面的数据也是有关联的,例如post就可以通过userId关联user,comment的postId可以关联post。

支持所有method:GET、POST、PUT、PATCH、DELETE。

支持HTTP、HTTPS调用。

也支持常用的URL书写方法,例如:获取帖子ID为1下的评论列表,可以写作/posts/1/comments,也可以写作/comments?postId=1。

取列表:

function getUsers() {
  fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => console.log(json))
}

取详情:

function getPostById(){
  fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then((response) => response.json())
    .then((json) => console.log(json));
}

新增:

function addPost(){
  fetch('https://jsonplaceholder.typicode.com/posts',{
    method:'POST',
    headers:{
      'Content-type':'application/json; charset=UTF-8'
    },
    body:JSON.stringfy({
      title:'标题',
      body:'内容',
      userId:2
    })
  }).then(response => response.json())
    .then(json => console.log(json))
}

当然,提交的数据并不会真的新增到服务端。修改、删除亦如此,不再赘述。

Dog API

页面上经常要展示图片,JSONPlaceholder虽然有photos,里面也有图片的URL和缩略图URL,但经我测试,很不稳定。

而Dog API能提供N多的狗狗图片,可以根据品种取,也可以取随机的。

例如(Vue):

<button @click="getDog">狗狗照片</button>
<hr>
<img :src="dogUrl" alt="狗狗图片">

const dogUrl = ref('https://images.dog.ceo/breeds/sheepdog-english/n02105641_5577.jpg')
function getDog() {
    fetch('https://dog.ceo/api/breeds/image/random')
        .then(response => response.json())
        .then(json => { dogUrl.value = json.message })
}


针对以上网络API,大家注意一下调用的频次,调用量别太大,也别太频繁,写个爬虫就在那扒,否则很容易被禁了。

json-server

上面的API接口,JSON结构是固定的,没法自定义。

在实际工作中,有时候服务端开发会先提供API文档,过一段时间才会提供可供调试的接口。在这段时间,前端开发如果想联调,可以使用json-server。

不需要掌握什么服务端开发语言,业务逻辑,会JSON就行。

安装:

npm install json-server

进入json-server目录后,创建db.json或者db.json5文件:


{
  carriers: [
    { id: '1', name: '货运公司A', vehicle_num: 100 },
    { id: '2', name: '货运公司B', vehicle_num: 200 },
  ],
  drivers: [
    { id: '1', name: '司机A', carrierId: 1 },
    { id: '2', name: '司机B', carrierId: 2 },
  ],
  profile: {
    name: 'freight',
  },
}

运行:

npx json-server db.json5

这样,我们就有几个端点可以访问了:

http://localhost:3000/carriers

http://localhost:3000/drivers

http://localhost:3000/profile

使用上跟前面的JSONPlaceholder基本一样。

还支持一些查询参数,例如等于=、小于lt、小于等于lte、大于ge、不等于ne。

GET /carriers?vehicle_num_lt=200

还支持范围查询,start、end、limit

GET /carriers?_start=0&_limit=1

分页:

GET /carriers?_page=1&_per_page=10

排序:

GET /carriers?_sort=-id

也可以增删改,数据也会真实地反映出来。

原文链接:,转发请注明来源!