Created
May 27, 2019 06:36
-
-
Save naoyeye/4764a8683768f10135e521aeb11e260b to your computer and use it in GitHub Desktop.
用于微信小程序
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* promise style request | |
*/ | |
import { decryptData, isNeedDecrypto } from './dec-data' | |
function createDefaultConfig () { | |
return { | |
url: '', | |
method: 'GET', | |
data: null, | |
header: { | |
'content-type': 'application/json' | |
}, | |
dataType: 'json' | |
} | |
} | |
function Request(config) { | |
let _config = Object.assign({}, createDefaultConfig(), config) | |
if (!_config.header) { | |
_config.header = {} | |
} | |
// set cookie in header | |
if (!_config.header.Cookie) { | |
let bid = wx.getStorageSync('bid') | |
_config.header.Cookie = `bid=${bid}` | |
} | |
if (!_config.header.Authorization) { | |
let access_token = wx.getStorageSync('access_token') | |
_config.header.Authorization = `Bearer ${access_token}` | |
} | |
const wxa_sessionid = wx.getStorageSync('wxa_sessionid') | |
_config.header.wxaSessionId = wxa_sessionid || null | |
return new Promise((resolve, reject) => { | |
let _url = _config.url | |
for (let key in _config.data) { | |
let reg = new RegExp(`:${key}`, 'gi') | |
_url = _url.replace(reg, _config.data[key]) | |
} | |
wx.request({ | |
url: _url, | |
method: _config.method, | |
data: _config.data, | |
header: _config.header, | |
success: (res) => { | |
let _res = res | |
if (isNeedDecrypto(_url, res.data) && res.statusCode === 200) { | |
let _data = decryptData(res.data) | |
_res = Object.assign({}, res, { | |
data: JSON.parse(_data) | |
}) | |
} | |
return resolve(_res) | |
}, | |
fail: (err) => { | |
return reject(err) | |
} | |
}) | |
}) | |
} | |
function createRequest(method) { | |
return function (url, data, header, dataType) { | |
return new Request({ | |
url, | |
data, | |
method, | |
header, | |
dataType | |
}) | |
} | |
} | |
const Fetch = { | |
get: createRequest('GET'), | |
post: createRequest('POST'), | |
put: createRequest('PUT'), | |
delete: createRequest('DELETE') | |
} | |
export default Fetch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment