基于做前端现在不用fetch就out的心态,我决定再现有的AngularJS项目中使用fetch代替angularJs的$http()方法
使用fetch封装成一个可以公用的js文件
import 'whatwg-fetch';
import 'es6-promise';
import 'promise-polyfill';
import 'isomorphic-fetch';
const objToQueryString = obj => {
let result = '';
for (let key in obj) {
result += '&' + key + '=' + encodeURIComponent(obj[key]);
}
if (result) {
result = result.slice(1);
}
return result;
};
const checkStatus = response => {
if ((response.status >= 200 && response.status < 300) || response.status === 304) {
return response;
}
const url = response.url;
const queryPos = url.indexOf('?');
let urlDo;
if (queryPos > 0) {
urlDo = url.substring(url.lastIndexOf('/') + 1, queryPos);
} else {
urlDo = url.substring(url.lastIndexOf('/') + 1);
}
throw new Error(`调用接口${urlDo}出错, 错误码${response.status}`);
};
export const get = (url, paramsObj) => {
if (paramsObj) {
url = url + '?' + objToQueryString(paramsObj);
}
return fetch(url, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json, text/plain, */*'
},
})
.then(checkStatus)
.then(response => response.json());
};
export const post = (url, paramsObj, bodyObj) => {
if (paramsObj) {
url = url + '?' + objToQueryString(paramsObj);
}
return fetch(url, {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: objToQueryString(bodyObj)
})
.then(checkStatus)
.then(response => response.json());
};
封装成一个可以公用的js文件的好处就是,每次使用fetch,只需要调用 fetch.js文件export出去的get方法或者post方法即可
具体使用
1,引入fetch.js文件
import {get, post} from '../../../utils/fetch';
2,调用get方法
getLeaderOpinion(params) {
get(path.offical.getLeaderOpinion, params).then(data=>{
});
},