react前端封装接口弹出错误_react中请求接口的封装

1. 新建一个dva项目。使用antd 或者antd-mobile组件库。

$ npm install dva-cli-g

$ dva-v

$ dvanewdva-quickstart

$ npm start

$  npm  install antd babel-plugin-import--save

或者是

$  npm  install antd-mobile babel-plugin-import--save

导入方式css

{

"entry":"src/index.js",

"env":{

"development":{

"extraBabelPlugins":[

"dva-hmr",

"transform-runtime",

["import",{"libraryName":"antd-mobile","style":"css"}]

]

},

"production":{

"extraBabelPlugins":[

"transform-runtime",

["import",{"libraryName":"antd-mobile","style":"css"}]

]

}

}

}

2. 在该项目的src中utils 创建名为request文件夹。

$ cd  dva-quickstart

$ cd  src

$ cd utils

新建文件夹名为request,然后在request文件夹下面创建名为helpers的文件夹以及index.js 和 README.md , request.js 如图所示:

在helpers 下建三个js文件 combineURL.js , isAbsoluteURL.js , serialize.js

combineURL.js中 :

604a4c426ab53e5648beea88bf267c21.png

isAbsoluteURL.js中 :

5cd8b6fe9dbfc7e455094e78bac5b71a.pngserialize.js中 :

3. 在utils下创建一个与request同级的lang.js

lang.js 如下:

exportconstisPresent=(obj)=>{

returntypeofobj!=='undefined'&&obj!==null;

};

exportconstisBlank=(obj)=>{

returntypeofobj==='undefined'||obj===null;

};

exportconstisBoolean=(obj)=>{

returntypeofobj==='boolean';

};

exportconstisNumber=(obj)=>{

returntypeofobj==='number';

};

exportconstisString=(obj)=>{

returntypeofobj==='string';

};

exportconstisArray=(obj)=>{

returnArray.isArray(obj)||Object.prototype.toString.call(obj)==='[object Array]';

};

exportconstisDate=(obj)=>{

returnobjinstanceofDate&&!isNaN(obj.valueOf());

};

exportconstisFunction=(obj)=>{

returntypeofobj==='function';

};

exportconstisJsObject=(obj)=>{

returnobj!==null&&(isFunction(obj)||typeofobj==='object');

};

exportconstisPromise=(obj)=>{

returnisPresent(obj)&&isFunction(obj.then);

};

exportconstisEmpty=(obj)=>{

if(isBlank(obj)){

returntrue;

}

if(obj.length===0){

returntrue;

}

for(constkeyinobj){

if(Object.prototype.hasOwnProperty.call(obj,key)){

returnfalse;

}

}

returntrue;

};

exportconstnormalizeBlank=(obj)=>{

returnisBlank(obj)?null:obj;

};

exportconstnormalizeBool=(obj)=>{

returnisBlank(obj)?false:obj;

};

exportconststringify=(token)=>{

if(isString(token)){

returntoken;

}

if(isBlank(token)){

returnString(token);

}

constret=token.toString();

constnewLineIndex=ret.indexOf('\n');

return(newLineIndex===-1)?ret:ret.substring(0,newLineIndex);

};

exportclassPromiseWrapper{

// Excutes promises one by one, e.g.

// const promise = () => new Promise(...)

// const promise2 = () => new Promise(...)

// sequentialize([ promise, promise2 ])

staticsequentialize=promiseFactories=>{

letchain=Promise.resolve();

promiseFactories.forEach(factory=>{

chain=chain.then(factory);

});

returnchain;

}

// Promise finally util similar to Q.finally

// e.g. finally(promise.then(...))

/* eslint-disable consistent-return */

staticfinally=(promise,cb)=>promise.then(res=>{

constotherPromise=cb();

if(typeofotherPromise.then==='function'){

returnotherPromise.then(()=>res);

}

},reason=>{

constotherPromise=cb();

if(typeofotherPromise.then==='function'){

returnotherPromise.then(()=>{

throwreason;

});

}

throwreason;

})

}

/* eslint-enable consistent-return */

exportclassStringWrapper{

staticequals=(s1,s2)=>s1===s2;

staticcontains=(s,substr)=>s.indexOf(substr)!==-1;

staticcompare=(a,b)=>{

if(a

return-1;

}elseif(a>b){

return1;

}

return0;

}

}

/* eslint-disable max-params */

exportclassDateWrapper{

staticcreate(

year,

month=1,

day=1,

hour=0,

minutes=0,

seconds=0,

milliseconds=0

){

returnnewDate(year,month-1,day,hour,minutes,seconds,milliseconds);

}

staticfromISOString(str){

returnnewDate(str);

}

staticfromMillis(ms){

returnnewDate(ms);

}

statictoMillis(date){

returndate.getTime();

}

staticnow(){

returnDate.now()||newDate();

}

statictoJson(date){

returndate.toJSON();

}

}

/* eslint-enable max-params */

这个是dva自动生成的request.js 把这个文件换下名字requests.js,它与lang.js同级。

4. 打开在request文件下request.js,进行编辑:

request.js

importfetchfrom'dva/fetch';

import{isEmpty}from'../lang';

importserializefrom'./helpers/serialize';

importcombineURLfrom'./helpers/combineURL';

importisAbsoluteURLfrom'./helpers/isAbsoluteURL';

import{apiBaseUrl}from'../../config';

import{Toast}from'antd-mobile';

constwait=ms=>newPromise(resolve=>setTimeout(resolve,ms));

consttimeout=(p,ms=30*1000)=>

Promise.race([

p,

wait(ms).then(()=>{

consterror=newError(`Connection timed out after ${ms} ms`);

error.statusCode=408;

throwerror;

}),

]);

// Request factory

functionrequest(url,options,method){

const{endpoint,...rest}=interceptRequest(url,options,method);

constxhr=fetch(endpoint,rest).then(interceptResponse);

returntimeout(xhr,request.defaults.timeout).catch((error)=>{

// return Promise.reject(error);

});

}

request.defaults={

baseURL:apiBaseUrl,

timeout:10*5000,

headers:{

Accept:'application/json',

},

};

// Headers factory

constcreateHeaders=()=>{

constheaders={

...request.defaults.headers,

};

// const auth = JSON.parse(localStorage.getItem('auth'+sessionStorage.getItem("hid")));

// const token = sessionStorage.getItem('token'); // 登录location获取到的token存放l

// if (auth) {

//   // Toast.info(`请稍等: ${token}`, 2);

//   // Toast.loading('');

//   headers.Authorization = auth.Token;

// } else if (token) {

//   // ;

//   // Toast.info(`请稍等: ${token}`, 2);

//   // Toast.loading('');

//   headers.Authorization = token;

// }

headers.Authorization="app";

returnheaders;

};

// Request interceptor

functioninterceptRequest(url,options,method){

letendpoint;

if(isAbsoluteURL(url)){

endpoint=url;

}else{

endpoint=combineURL(request.defaults.baseURL,url);

}

letdata={

method,

endpoint,

headers:createHeaders(),

};

if(!isEmpty(options)){

data={

...data,

...options,

};

if(options.json){

data.headers['Content-Type']='application/json;charset=utf-8';

data.body=JSON.stringify(options.json);

}

if(options.form){

data.headers['Content-Type']='application/x-www-form-urlencoded;charset=utf-8';

data.body=serialize(options.form);

}

if(options.body){

data.body=options.body;

constauth=JSON.parse(localStorage.getItem('auth'+sessionStorage.getItem("hid")));

if(auth){

if(auth&&options.bodyinstanceofFormData&&!options.body.hasPatientid){

// options.body.append('patientid', auth.Patientid);

}

}

}

if(options.params){

endpoint+=`?${serialize(options.params)}`;

data.endpoint=endpoint;

}

}

returndata;

}

// Response interceptor

/* eslint-disable consistent-return */

functioninterceptResponse(response){

returnnewPromise((resolve,reject)=>{

constemptyCodes=[204,205];

// Don't attempt to parse 204 & 205

if(emptyCodes.indexOf(response.status)!==-1){

returnresolve(response.ok);

}

if(response.ok){

constcontentType=response.headers.get('Content-Type');

if(contentType.includes('application/json')){

resolve(response.json());

}

resolve(response);

}

if(response.status===401){

// return Toast.fail('认证信息已过期,请重新登录', 2, () => {

// return Toast.fail('请重新登录', 2, () => {

localStorage.removeItem('auth'+sessionStorage.getItem("hid"));

// sessionStorage.removeItem('token');

location.reload();

// TODO:跳转登录路由

// });

}

consterror=newError(response.statusText);

try{

response.clone().json().then((result)=>{

error.body=result;

error.response=response;

reject(error);

});

}catch(e){

error.response=response;

reject(error);

}

});

}

/* eslint-enable consistent-return */

// suger

request.get=(url,options)=>request(url,options,'GET');

request.head=(url,options)=>request(url,options,'HEAD');

request.options=(url,options)=>request(url,options,'OPTIONS');

request.post=(url,options)=>request(url,options,'POST');

request.put=(url,options)=>request(url,options,'PUT');

request.delete=(url,options)=>request(url,options,'DELETE');

request.del=request.delete;

exportdefaultrequest;

5. 这样你就可以在今后的项目正常使用按照以下步骤

module.exports={

apiBaseUrl:"http://172.118.100.50/api/",

};

之后再services文件下就可以这样去下啦:

importrequestfrom'../utils/request/request';

exportfunctionqueryScaleMenu(start,limit){

constbody=newFormData();

body.append('start',start);

body.append('limit',limit);

returnrequest.post('news/menu/query',{body});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值