4 Star 0 Fork 0

时辰 / sloth-web

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
request.js 3.07 KB
一键复制 编辑 原始数据 按行查看 历史
bijh 提交于 2016-09-30 17:00 . .
// import Toast, {ToastErrorStyle} from "./components/Toast"
import qs from "qs"
import {apihost, apiversion, debug} from "./app_config"
import { SLOTH_TOKEN } from "./const"
import Toast from './src/components/Toast'
import Login from './src/components/Login'
import Loading from './src/components/Loading'
import EventEmitter from "./src/common/EventEmitter"
import 'whatwg-fetch'
// import RCTDeviceEventEmitter from "RCTDeviceEventEmitter"
var log_enable = debug
export let BusinessException = function (json) {
this.info = json
}
export let NothingException = function () {}
export default async function ({url, params, type = "GET", host = apihost, headerHost}) {
let headers = {
'Accept':'application/json',
'Content-Type':'application/json'
}
if (headerHost) {
headers.ApiHost = headerHost
}
let tokenString = await localStorage.getItem(SLOTH_TOKEN)
let token = JSON.parse(tokenString)
if (token && token.accessToken) {
Object.assign(headers, {
"Authorization": "Bearer " + token.accessToken
})
}
var request = {
mode: 'cors',
method: type,
headers: headers
}
var query = ''
if (params) {
if (type !== 'GET' && type !== 'HEAD') {
request['body'] = JSON.stringify(params)
} else {
query = qs.stringify(params)
}
}
var u = host + url
// if (url.startsWith("http://") || url.startsWith("https://")) {
// u = url
// }
if (query && query !== '') {
u = u + "?" + query
}
let modal = {}
if (type !== "GET" && type !== 'HEAD') {
Loading.show()
}
if (log_enable) console.log('fetch:' + token + ',' + type + ',' + u + ',' + JSON.stringify(params))
let response = await fetch(u, request)
let text = await response.text()
if (log_enable) console.log('response:' + response.status + ',' + text)
if (type !== "GET") {
Loading.close()
}
if ((response.status >= 200 && response.status <= 208) || response.status === 226) {
let json = JSON.parse(text)
return json
}
if (response.status === 400) {
let json = JSON.parse(text)
let forBusiness = false
for (let key in json) {
if (json.hasOwnProperty(key) && key !== "message") {
forBusiness = true
}
}
if (forBusiness) {
throw new BusinessException(json)
} else {
Toast.show(json.message, 'warn')
throw new NothingException()
}
}
if (response.status === 401 || response.status === 403) {
Login.show();
EventEmitter.emit("request_logout")
// todo: emit request_logout event
if (response.status === 401) {
// Toast.show('帐号未登录', 'warn')
} else {
Toast.show('会话超时', 'warn')
}
throw new NothingException()
}
if (debug) {
Toast.show(text, 'warn')
} else {
Toast.show("服务端系统错误!", 'warn')
}
throw new Error()
}
1
https://gitee.com/twoours/sloth-web.git
git@gitee.com:twoours/sloth-web.git
twoours
sloth-web
sloth-web
master

搜索帮助