Fetch.js

2018-06-05  本文已影响0人  pilakuma

import * as helper from './helper.js'

import Cookies from 'js-cookie'

export default async(url = '', data = {}, type = 'GET', method = 'fetch',body = null) => {

type = type.toUpperCase();

url = url;

if(data){

if (type == 'GET' || type == 'POST') {

let dataStr = ''; //数据拼接字符串

Object.keys(data).forEach(key => {

dataStr += key + '=' + data[key] + '&';

})

if (dataStr !== '') {

dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));

url = url + '?' + dataStr;

}

}

}

if (method == 'fetch') {

let requestConfig = {

method: type,

headers: {

'Accept': 'application/json',

'Content-Type': 'application/json',

'x-token': Cookies.get('token')

},

mode: "cors",

        cache: type =='POST' || type == 'GET'?"no-cache":"no-cache"

}

if(body){

requestConfig.body = JSON.stringify(body);

console.log(url)

console.log(requestConfig)

}

try {

const response = await fetch(url, requestConfig);

const responseJson = await response.json();

helper.log('fetch:' + url);

helper.log(responseJson);

return responseJson

} catch (error) {

throw new Error(error)

}

} else {

return new Promise((resolve, reject) => {

let requestObj;

if (window.XMLHttpRequest) {

requestObj = new XMLHttpRequest();

} else {

requestObj = new ActiveXObject;

}

let sendData = '';

if (type == 'POST') {

sendData = JSON.stringify(data);

}

requestObj.open(type, url, true);

requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

requestObj.send(sendData);

requestObj.onreadystatechange = () => {

if (requestObj.readyState == 4) {

if (requestObj.status == 200) {

let obj = requestObj.response

if (typeof obj !== 'object') {

obj = JSON.parse(obj);

}

resolve(obj)

} else {

reject(requestObj)

}

}

}

})

}

}

上一篇下一篇

猜你喜欢

热点阅读