fetch的总结

// 通过fetch获取内容
/**
* Headers=='application/json'
*
*/
fetch('/marketStrategy/getTagNodeTree?id=' + treeNode.props.eventKey,
{
// 在URL中写上传递的参数
method: 'GET',
headers: new Headers({
'Accept': 'application/json' // 通过头指定,获取的数据类型是JSON
})
})
.then((res) => {
return res.json();
})
.then((res) => {
// var list = res.list;
// let parse = JSON.parse(res);
// console.log('resresres============' + JSON.stringify(parse.list));
treeNode.props.dataRef.children = res.list;
this.setState({
treeData: [...this.state.treeData],
});
})
// post请求的列表
// 请求成功了status ==200----300做一个判断,不然400---500也会返回到这里
// fetch不支持jsonp

fetch(
'/marketStrategy/list',
{
method: 'POST',
mode: "no-cors",
headers: new Headers({
'Accept': 'application/json', // 通过头指定,获取的数据类型是JSON
'Content-Type': 'application/x-www-form-urlencoded'
}),
credentials: 'include', // 强制加入凭据头
body: new URLSearchParams([]).toString()
})
.then((Response) => {
if (Response.status >= 200 && Response.status < 300) {
return Response.json();
} else {
return { code: Response.status }
}
})
.then((res) => {
console.log(res)
})

//对于fetch的封装
var Event = {
Post: function (url, options) {
var that = this;
that.commonHttp(url, options, 'POST');
},
Get: function (url, options) {
var that = this;
that.commonHttp(url, options, 'GET');
},
commonHttp: function (url, options, type) {
var Obj = {
method: type,
headers: new Headers({
'Accept': 'application/json' // 通过头指定,获取的数据类型是JSON
}),
credentials: 'include',
};
if (type === 'GET') {
var urlParame = '';
for (var i in options) {
urlParame += options[i] + '&';
}
url += '?' + urlParame;
}
if (type === 'POST') {
Obj.headers = new Headers({
'Accept': 'application/json', // 通过头指定,获取的数据类型是JSON
'Content-Type': 'application/x-www-form-urlencoded'
})
var arr = [];
for (let item in options) {
arr.push([item, options[item]]);
}
Obj.body = new URLSearchParams(arr).toString();
}
fetch(url, Obj).then((res) => {
if (res.status >= 200 && res.status < 300) {
return res.json;
}
}).then((res) => {
return res;
})
}
}
Event.Post('utrl', { a: 1 });
Event.Get('url',{b:1});
posted @ 2018-09-04 17:13  focus_yaya  阅读(201)  评论(0编辑  收藏  举报