fetch.js 1.6 KB
Newer Older
M
udpata  
maguohua 已提交
1
import {baseUrl} from './env'
M
udpata  
maguohua 已提交
2

M
maguohua 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
export default async (type = 'GET', url = '', data = {}) => {
	type = type.toUpperCase();
	url = baseUrl + url;

	if (type == 'GET') {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}

	if (window.fetch) {
		let requestConfig = {
M
updata  
maguohua 已提交
21
			credentials: 'include',
M
udpata  
maguohua 已提交
22 23 24
		  	method: type,
		  	headers: {
		      	'Accept': 'application/json',
M
maguohua 已提交
25
	  			'Content-Type': 'application/json'
M
udpata  
maguohua 已提交
26
		  	},
M
maguohua 已提交
27 28
		  	mode: "cors",
		  	cache: "only-if-cached"
M
udpata  
maguohua 已提交
29 30
		}

M
maguohua 已提交
31 32
		if (type == 'POST') {
			Object.defineProperty(requestConfig, 'body', {
M
udpata  
maguohua 已提交
33 34
				value: JSON.stringify(data)
			})
M
maguohua 已提交
35 36 37 38 39 40 41
		}

		try {
			var response = await fetch(url, requestConfig);
			var responseJson = await response.json();
		}catch (error){
			throw new Error(error)
M
udpata  
maguohua 已提交
42 43
		}
		
M
maguohua 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
		return responseJson
	}else{
		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);
					}
					return obj
				}else {
					throw new Error(requestObj)
				}
			}
		}
	}
M
udpata  
maguohua 已提交
76
}