react中前端同学如何模拟使用后端接口操作数据?

为什么前端同学需要模拟后端数据

作为一个前端,在实现项目功能的时候,需要在前端写一个静态的json数据,进行测试。

项目中后端的接口往往是较晚才会出来,并且还要写接口文档,于是我们的前端的许多开发都要等到接口给我们才能进行开发。

为了方便前端代码自测,提高开发效率,可以模拟生成数据进行前后端数据联调。

而且有的时候,还需要涉及到全模拟请求以及请求回来的过程,实现动态增删改查。

这个时候就需要使用到web的API接口神器json-server。

json-server文档:https://www.npmjs.com/package/json-server

之前介绍过如何利用json-server搭建模拟后端服务器

json-server 是一个 Node 模块,运行 Express 服务器,你可以指定一个 json 文件作为 api 的数据源。
json-server 可> 以直接把一个json文件托管成一个具备全RESTful风格的API。

公众号:前端爱好者

有了它,前端同学终于可以硬气的干活了。。。

为什么选择json-server

之前是采用easy-mock,遗憾的是其只能使用 get 请求。

json server 作为工具

  • 足够简单,
  • 写少量数据,
  • 支持CORS和JSONP跨域请求,
  • 支持GET, POST, PUT, PATCH 和 DELETE 方法,
  • 更提供了一系列的查询方法,分页,排序等操作,简直强大

也不用等到后端开发同事接口写好了之后再去对接接口了。

只需要借助json-server这个神器可以完美模拟业务。

使用json-server进行增删改查操作

前期准备 – 封装fetch

Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。

它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。

这种功能以前是使用 XMLHttpRequest 实现的。

前端老兵,公众号:前端爱好者

react开发利器 之 fetch请求封装

使用json-server进行增删改查操作

json-server 可以用于模拟请求 ----Restful风格

  • 查询 get params:{}
  • 增加 post data:{}
  • 删除 delete
  • 修改 put /patch data:{}

公共暴露API接口文件 – api.js

// api.js

import requestFun from "./fetchUtil"; //引入
import qs from "qs";

const { stringify } = qs;
const { post, get, deleteMethod,patch} = requestFun;

其中fetchUtil.js为封装的Fetch请求

查询 get params:{}

// api.js 
// 简单查询
export async function fetchGetRoles(id,params) { 
  return get(`http://localhost:8001/roles`, params);
}

// 联表查询
export async function fetchGetMenus(params) {
  return get(`http://localhost:8001/rights?_embed=children`, params);
}

组件中使用

import {  fetchGetRoles, fetchGetMenus} from "../../utils/api"; // 引入api文件

// 简单查询
const fetchGetRolesListHandle = async () => {
    const urseListData = await fetchGetRoles();
    serolesList(urseListData);
};
fetchGetRolesListHandle();

const fetchGetRolesListHandle = async () => {
    const menusListData = await fetchGetMenus(); 
};

增加 post data:{}

// api.js 
// post方式
export async function fetchAddUser(params) {
  return post(`http://localhost:8001/users`, params);
}

组件中使用

import {  fetchAddUser } from "../../utils/api"; // 引入api文件

// 调用接口
const data = await fetchAddUser({
    ...values, // 注意这里
    roleState: true,
    default: false,
}); 

删除 delete

// api.js 

// delete 方式 
export async function fetchDeleteRoles(id) { 
    return deleteMethod(`http://localhost:8001/roles/${id}`);
}

组件中使用

import {  deleteMethod } from "../../utils/api"; // 引入api文件

// 调用接口
const deleteRolesMethod = async (item) => { 
  const data = await fetchDeleteUser(item.id);
};

修改 put /patch data:{}

// api.js 
// patch
export async function fetchPatchUser(id,params) { 
  return patch(`http://localhost:8001/users/${id}`, params);
}

组件中使用

import {  fetchPatchUser } from "../../utils/api"; // 引入api文件

// 状态修改
const handelChange = async (item) => { 
  // 发送请求到后端
  await fetchPatchUser(item.id, { roleState: item.roleState });
};

全部代码

// api.js

import requestFun from "./fetchUtil"; //引入
import qs from "qs";

const { stringify } = qs;
const { post, get, deleteMethod,patch} = requestFun;


// 简单查询
export async function fetchGetRoles(id,params) { 
  return get(`http://localhost:8001/roles`, params);
}

// 联表查询
export async function fetchGetMenus(params) {
  return get(`http://localhost:8001/rights?_embed=children`, params);
}

// 复杂查询
export async function fetchGetAuditNewsList(params) { 
  return get(`http://localhost:8001/news?author=${params.author}&auditState_ne=${params.auditState}&publishState_lte=${params.publishState}&_expand=category`);
}

// post方式
export async function fetchAddUser(params) {
  return post(`http://localhost:8001/users`, params);
}

// delete 方式 
export async function fetchDeleteRoles(id) { 
    return deleteMethod(`http://localhost:8001/roles/${id}`);
}

// patch
export async function fetchPatchUser(id,params) { 
  return patch(`http://localhost:8001/users/${id}`, params);
}

其实,文件中http://localhost:8001完全可以使用代理转发,这里暂不赘述。

补充 put和patch的区别

put和patch都可以进行修改操作

区别

  • put 方式如果没有将所有属性都写完整 没写的属性会丢失
  • patch方式没修改的属性不写默认为之前的值

举例:

{id:1,name:"zs",age:18}

修改age=20

put:{id:1,age:20}
patch:{id:1,name:"zs",age:20} 

json-server 高级用法

Filter

使用.操作 对象属性值,比如访问更深层次的属性

GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode

Paginate

使用 _page 和可选的 _limit来对返回数据定制(不设置默认返回10条)。

在返回的Response Headers 中,有一个属性Link,里面会有first, prev, next and last links

GET /posts?_page=7
GET /posts?_page=7&_limit=20

10 items are returned by default

Sort

使用 _sort_order (默认是ascending)

GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc

对于多字段的排序, 可以这样

GET /posts?_sort=user,views&_order=desc,asc

Slice

使用 _start _end 或者 _limit (an X-Total-Count header is included in the response)

GET /posts?_start=20&_end=30
GET /posts/1/comments?_start=20&_end=30
GET /posts/1/comments?_start=20&_limit=10

Works exactly as Array.slice (i.e. _start is inclusive and _end exclusive)

Operators

使用 _gte_lte 选取一个范围

GET /posts?views_gte=10&views_lte=20

使用 _ne 排除一个值

GET /posts?id_ne=1

使用 _like 进行模糊查找 (支持正则表达式)

GET /posts?title_like=server

Full-text search (全文检索)

使用 q,在对象全部value中遍历查找包含指定值的数据

GET /posts?q=internet

Relationships (关系图谱)

获取包含下级资源的数据, 使用 _embed

GET /posts?_embed=comments
GET /posts/1?_embed=comments

获取包含上级资源的数据, 使用 _expand

GET /comments?_expand=post
GET /comments/1?_expand=post

To get or create nested resources (by default one level, add custom routes for more)

GET  /posts/1/comments
POST /posts/1/comments

Database

GET /db

Homepage

Returns default index file or serves ./public directory

GET /

json-server github地址 : https://github.com/typicode/json-server

参考文档

  • https://gitcode.net/mirrors/typicode/json-server
  • https://www.npmjs.com/package/json-server
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端布道人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值