react 版权问题_react使用fetch封装请求的方法-简单易懂
方法有很多种,这里贴一个比较优雅又简单易懂的。用class类写法,new一个实例方法。
其中qs是包,类似于url拼接的方法,自行npm安装。我这里fetch使用的是dva的fetch,也可以自行使用自带的fetch ,
把const fetch = require('dva').fetch; 注释既可。
/**
* 请求方法
*/
import qs from 'qs';
import { message } from 'antd';
const fetch = require('dva').fetch;
const { stringify, parse } = qs;
const checkStatus = res => {
if (200 >= res.status < 300) {
return res;
}
message.error(`网络请求失败,${res.status}`);
const error = new Error(res.statusText);
error.response = response;
throw error;
};
/**
* 捕获成功登录过期状态码等
* @param res
* @returns {*}
*/
const judgeOkState = async res => {
const cloneRes = await res.clone().json();
//TODO:可以在这里管控全局请求
if (cloneRes.code !== 200) {
message.error(`${cloneRes.msg}${cloneRes.code}`);
}
return res;
};
/**
* 捕获失败
* @param error
*/
const handleError = error => {
if (error instanceof TypeError) {
message.error(`网络请求失败啦!${error}`);
}
return { //防止页面崩溃,因为每个接口都有判断res.code以及data
code: -1,
data: false,
};
};
class http {
/**
*静态的fetch请求通用方法
* @param url
* @param options
* @returns {Promise}
*/
static async staticFetch(url = '', options = {}) {
const defaultOptions = {
/*允许携带cookies*/
credentials: 'include',
/*允许跨域**/
mode: 'cors',
headers: {
token: null,
Authorization: null,
// 当请求方法是POST,如果不指定content-type是其他类型的话,默认为如下↓,要求参数传递样式为 key1=value1&key2=value2,但实际场景以json为多
// 'content-type': 'application/x-www-form-urlencoded',
},
};
if (options.method === 'POST' || 'PUT') {
defaultOptions.headers['Content-Type'] = 'application/json; charset=utf-8';
}
const newOptions = { ...defaultOptions, ...options };
console.log('newOptions', newOptions);
return fetch(url, newOptions)
.then(checkStatus)
.then(judgeOkState)
.then(res => res.json())
.catch(handleError);
}
/**
*post请求方式
* @param url
* @returns {Promise}
*/
post(url, params = {}, option = {}) {
const options = Object.assign({ method: 'POST' }, option);
//一般我们常用场景用的是json,所以需要在headers加Content-Type类型
options.body = JSON.stringify(params);
//可以是上传键值对形式,也可以是文件,使用append创造键值对数据
if (options.type === 'FormData' && options.body !== 'undefined') {
let params = new FormData();
for (let key of Object.keys(options.body)) {
params.append(key, options.body[key]);
}
options.body = params;
}
return http.staticFetch(url, options); //类的静态方法只能通过类本身调用
}
/**
* put方法
* @param url
* @returns {Promise}
*/
put(url, params = {}, option = {}) {
const options = Object.assign({ method: 'PUT' }, option);
options.body = JSON.stringify(params);
return http.staticFetch(url, options); //类的静态方法只能通过类本身调用
}
/**
* get请求方式
* @param url
* @param option
*/
get(url, option = {}) {
const options = Object.assign({ method: 'GET' }, option);
return http.staticFetch(url, options);
}
}
const requestFun = new http(); //new生成实例
export const { post, get, put } = requestFun;
export default requestFun;
如何调用
import requestFun from '../utils/fetchUtil';
import qs from 'qs';
const { stringify } = qs;
const {post,get} = requestFun;
//get方式
export async function fetchData1(params) {
return get(`/api/bbb?${stringify(params)}`);
}
//post方式
export async function fetchData2(params) {
return post(`/api/aaa`,params);
}
有问题可以提出~~~,应该没多大问题
以上就是react使用fetch封装请求的方法-简单易懂的全部内容。
react 版权问题_react使用fetch封装请求的方法-简单易懂相关推荐
- 使用fetch封装请求_关于如何使用Fetch API执行HTTP请求的实用ES6指南
使用fetch封装请求 In this guide, I'll show you how to use the Fetch API (ES6+) to perform HTTP requests to ...
- vue如何封装请求接口方法
vue如何封装请求接口方法 方法一 首先创建一个server.js文件 引入axios和qs //引入axios和qs插件 import axios from 'axios' import qs fr ...
- uniapp封装请求的方法(luch-request插件使用)
1.安装luch-request npm i luch-request -S 2.设置根地址 新建一个baseUrl目录 ,设置一个url.js //基础Api const BASE_API=&quo ...
- react 版权问题_react兼容ie
使用最新版本的 create-react-app(v2.1.0)创建 react 项目时,在 IE 9 & IE 10 中碰到了"Map未定义"的报错: 很明显,这是 IE ...
- react 类暴露_react如何将组件内部的方法暴露给外部
最近在项目中遇到一个问题,就是需要在类的外部调用操作类内部的方法. 举个例子,我有一个Toast组件,在外部需要调用它的show方法来控制他的显隐状态. 之前我的写法是写一个静态类方法,然后在cons ...
- 小程序promise封装post请求_微信小程序 es6-promise.js封装请求与处理异步进程
微信小程序 es6-promise.js封装请求与处理异步进程 下载es6-promise.js置于根目录下的libs文件夹下: 在根目录utils文件夹下新建httpsPromisify.js,即定 ...
- React Native Fetch封装那点事...
每一门语言都离不开网络请求,有自己的一套Networking Api.React Native使用的是Fetch. 今天我们来谈谈与Fetch相关的一些事情. purpose 通过这篇文章,你将了解到 ...
- React Native从零开始(七)Fetch网络请求
React Native从零开始(七)Fetch网络请求 先上效果图 因为网络请求比较简单,所以我们直接先开始看语法然后看这个GET和POST不同的实现就好. 一.语法使用 /*语法:fetch(参数 ...
- 使用fetch封装ajax_如何使用Fetch在JavaScript中进行AJAX调用
使用fetch封装ajax I will be sharing bite sized learnings about JavaScript regularly in this series. We'l ...
最新文章
- 【jsp】兴唐第三十节课作业
- 关于使用JAVA中JDK安装和在命令行中编译和运行程序的一些总结
- sql server转oracle需要注意的几点
- Jenkins创建Maven项目及SSH部署
- jzoj3362,bzoj3758-[NOI2013模拟]数数【分段打表,背包,状压】
- 再等等!iPhone 11和iPhone SE还会继续降价
- hibernate版本_基于jsp+mysql+Spring+hibernate+Struts 2的SSH在线蛋糕销售网站平台管理系统...
- 本地函数定义是非法的_使用函数计算三步实现深度学习 AI 推理在线服务
- HDU.2111 Saving HDU(贪心)
- Sensor系列之aDSP端Sensor Driver流程
- 智慧监狱UWB定位系统解决方案
- 不加群提取群成员_使用itchat分析指定微信群男女比例等成员数据
- FFmpeg转换ts为mp4
- 《小狗钱钱》读书笔记
- MATLAB 如何让图形变美?[第一期]
- Hexo个人博客绑定域名
- Linux虚拟机不显示IP地址的三种解决方法
- matlab中elevation函数功能,Matlab的Demcmap的Python等价物(elevation+/appropriate colormap)...
- 威客生存手册——从新手到职业威客的蜕变
- 三种离婚男人该去面壁思过
热门文章
- Xamarin for iOS 11(一) - 初尝ARKit
- 谈一下我们是怎么做数据库单元测试(Database Unit Test)的
- 离线安装 VS2017 的正确姿势
- PHP获取当前页面URL
- 计算机基础知识的文献,四 计算机文献检索基础知识(原理、结构和功能)
- 【ArcGIS风暴】ArcGIS10.6创建LAS数据集的两种方法并加载点云数据
- Android之实现首尾带圆角的多颜色水平条
- Android之解决Android8.0手机(Notification)收不到自定义消息通知以及其它手机得到数据不同步
- linux c之解决使用socket函数返回为0的问题
- linux 配置path