simple-mock-api

本文介绍如何使用json-server快速搭建一个简易的Mock API服务,支持数据实时刷新和自定义请求处理,适用于项目开发中需要模拟数据的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中有一个Activiy需要轮询多个接口,实时刷新数据。这里很多业务逻辑都需要依赖当前的状态,所以简单写了一个服务端,用于生成一些mock data,并且支持数据实时刷新。

项目地址:simple-mock-api

挂到腾讯云上就可以公网访问了。


simple-mock-api

Use json-server make this simple mock api server.

Usage

  1. checkout this project,and cd
  2. type npm install in terminal to install dependences
  3. run node app.js
  4. get result via your configed cgi,like http://localhost:3000/get_match_players

Config

You can config

cgi,
default json file,
custom handle the request, modify json response

Example

Create a get_match_detail.json file in data folder.

{
  "state": 1,
  "title":"NBA",
  "time":"2017-01-01",
  "homescore": "101",
  "guestscore": "115"
}

In config.js config you mock api

var config = [
{
    "cgi":"/get_match_detail",
    "filepath":"data/get_match_detail.json",
    "need_cache":true,
    "hookfunc":func_get_match_detail
},
{
    "cgi":"/get_match_players",
    "filepath":"data/get_match_players.json",
    "need_cache":false,
    "hookfunc":func_get_match_players
},

];

You can custom handle the request by define your custom “hookfunc”, like this:

var func_get_match_detail = function(defaultObj,req) {
    //increase homescore every time
    var homescore = parseInt(defaultObj.homescore)+1+"";
    defaultObj.homescore = homescore;
}

The param defaultObj means the parsed json object you defined in the key “filepath”.

If the key “need_cache” seted true, than your hookfunc can change the defaultObj in the cache forever.

Start JSON Server

$ node app.js

Now if you go to http://localhost:3000/get_match_detail, you’ll get

{
  "state": 1,
  "title":"NBA",
  "time":"2017-01-01",
  "homescore": "102",
  "guestscore": "115"
}

and the homescore’s value changed every time when you go to the same link.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值