npmchenwei111
Version:
test1111
122 lines (110 loc) • 2.83 kB
JavaScript
/**
* Created by ziyu on 2017/6/15.
*/
import YTInvokeNetworkQuery from '../../src/native/YTInvokeNetworkQuery'
import net from '../config/Net'
function parseJSON (response) {
return response.json()
}
function checkStatus (response) {
if (response.status >= 200 && response.status < 300) {
return response
}
console.log('HttpTag checkStatus error', response)
const error = new Error(`Request Failed, because of statusCode = ${response.status}`)
error.response = response
throw error
}
/**
* 暴力合并url
* @param baseUrl 请保证 baseUrl后面没有/
* @param apiName
* @returns {*}
*/
function mergeUrl (baseUrl, apiName) {
if (baseUrl.endsWith('/') && apiName.startsWith('/')) {
return baseUrl + apiName.substring(1)
}
if (!baseUrl.endsWith('/') && !apiName.startsWith('/')) {
return baseUrl + '/' + apiName
}
return baseUrl + apiName
}
/**
* 请求方法
* @param type
* @param baseUrl
* @param apiName
* @param body
* @param header
* @returns {Promise.<TResult>|*}
*/
function requestUrl (type, baseUrl, apiName, body, header) {
return YTInvokeNetworkQuery.getNetworkQuery(body).then(res => {
return fetch(mergeUrl(baseUrl, apiName), {
method: type,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
...header
},
timeout: 20,
mode: 'cors',
body: res
}).then(checkStatus, function (error) {
throw error
}).then(parseJSON, function (error) {
throw error
}).then((result) => {
console.log('HttpTag', result)
return result
}, function () {
return {msg: '网络访问失败,请稍后重试。'}
})
}).catch(error => {
console.log('HttpTag', 'params error' + error)
return {msg: '请求参数出错'}
})
}
/**
* 判断baseUrl
* 目前用最简单的判断 openapp开头就是baseUrl_openapi
* @param apiName
*/
function judgeBaseUrl (apiName) {
let api = net.getApi()
if (apiName && (apiName.startsWith('/openapp/') || apiName.startsWith('openapp/')
|| apiName.startsWith('/youjie/') || apiName.startsWith('youjie/'))) {
return api.baseUrl_openapi
}
return api.baseUrl_fapi
}
/**
* 请求for JKZJ
* @param url
* @param body
* @param header
* @returns {Promise}
*/
export function fetchPost (url, body, header) {
return requestUrl('POST', judgeBaseUrl(url), url, body, header)
}
/**
*
* @param url
* @param body
* @returns {Promise}
*/
export function fetchPostPromise (url, body, header) {
return new Promise((resolve, reject) => {
fetchPost(url, body, header).then(res => {
if (res.code === 0) {
resolve(res)
} else {
reject(res.msg)
}
}).catch(err => {
reject((err && err.msg) ? err.msg : err)
})
})
}