1.0.0 • Published 2 years ago
@liaoyunong/dataservice v1.0.0
dataService
用fetch发起网络请求
安装
yarn add @liaoyunong/dataservice // 建议使用 yarn 安装
Import
import { getJSON } from '@liaoyunong/dataservice'
使用
1. POST
getJSON( url, params ) // parmas 为可选项
.then((data)=>{
// to do when request succeeded
onsuccess();
})
.catch((err)=>{
// to do when request failed
onerror();
})
注:对于多层结构的 params 使用了类 jquery.param 方法处理,参考 jQuery.param()
2. GET
getJSON( url, params, { method: "GET" } )
.then(onsuccess) // 即 data => success(data)
.catch(onerror) // 即 err => onerror(data)
3. Upload
// 新建 formData 将 media 标签内取出的 Blob 对象 append 到 formData 内
let uploadFile = new FormData()
uploadFile.append( 'file', input.files[0] )
uploadFile.append( 'name', 'userIcon' )
// uploadFile 为 formData
getJSON( url, uploadFile )
.then(onsuccess) // 即 data => success(data)
.catch(onerror) // 即 err => onerror(data)
4. JSONP
需单独引入 getJsonp 方法
import { getJsonp } from '@liaoyunong/dataservice'
getJsonp( url )
.then(( json, response ) => {
console.log(json) // response.json() 解析后的对象,如 {title: '获取学员信息', userName: 'mercury'}
console.log(response) // 请求返回的完整相应
})
.catch(onerror) // 即 err => onerror(data)
配置
1. request
- 默认值
if (typeof req_params == 'string') {
contentType = 'application/json';
}
else {
contentType = "application/x-www-form-urlencoded; charset=UTF-8";
}
const options = {
method: 'POST',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': contentType,
'X-Requested-With': 'XMLHttpRequest'
},
credentials: 'same-origin',
cache: 'no-cache'
};
// FormData
delete options.headers; //fetch 会自动添加相应的content-type 为 multipart/form-data; boundary=...
- 配置
const options = {
method: 'GET',
headers: {
'Accept': 'image/gif',
'Content-Type': contentType, // 一般不需要,有特殊需要则配置
},
/**
JsonDTO: { // 可选配置,配置成功则对本次请求生效,不影响全局JsonDTO设置
flag: 'rs',
message: 'rsmsg',
data: 'rsdata'
}
JsonDTO: 'RAW' // 配置为RAW后,本次请求会在resolve时拿到完整的数据,全局JsonDTO将在本次请求中失效
**/
};
getJSON( url, params, options )
2. response
- 默认值
const JsonDTO = {
flag: 'flag',
message: 'message',
data: 'data'
};
// 默认解析的 response 字段
const successFlag = 1; // 成功
const failFlag = 0; // 失败
// 标志位值
const extraFlagMissions = [];
// 额外的 flag 和 mission [{flag: -1, mission: (data, resData) => console.log(data, resData)}]
const badStatus = [];
// 如果请求失败,配置返回状态对应的回调 [{status: 401, callback: () => window.location.href = '#/login'}]
- 配置
// 均为可选项
const resParams = {
JsonDTO,
successFlag,
failFlag,
extraFlagMissions,
badStatus,
}
getJSON.initHttpDTO(resParams); // 将配置对象传入
1.0.0
2 years ago