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中 :
isAbsoluteURL.js中 :
serialize.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});
}