smart-admin/rc-busness/config/async/fetch.js
lin 9f955a34eb 迭代功能需求
1.修改用户信息存储位置
2.修复订单显示的问题
3.修改优惠卷显示文字显示和选择提示
4.修复地址列表排版错位的问题
5.添加搜索链接跳转查询
2022-03-23 18:04:14 +08:00

94 lines
2.2 KiB
JavaScript

import {
baseUrl
} from './env';
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
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 (fetch && method === 'fetch') {
let token='';
if(process.client) {
token = localStorage.getItem("token");
// let tokenStr = localStorage.getItem("userInfo");
// if(tokenStr){
// tokenStr = JSON.parse(tokenStr);
// if(tokenStr && tokenStr.xaccessToken)
// token=tokenStr.xaccessToken;
// }
}
let requestConfig = {
method: type,
headers: {
// 'Accept': 'text/plain',
'Content-Type': 'application/json',
'x-access-token': token
},
mode: 'cors',
// channelId:'H5@2021',
cache: 'force-cache'
}
if (type === 'POST') {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data)
})
}
try {
const response = await fetch(url, requestConfig)
const responseJson = await response.json()
return responseJson
} catch (error) {
throw new Error(error)
}
} else {
return new Promise((resolve, reject) => {
let requestObj
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest()
}
let sendData = ''
if (type === 'POST') {
sendData = JSON.stringify(data)
}
requestObj.open(type, url, true)
requestObj.setRequestHeader('Content-Type', 'application/json')
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)
}
}
}
})
}
}