Created
September 26, 2018 10:12
-
-
Save ibreathebsb/c8973529e8dea292c9489bdc76627e8f 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
import * as qs from 'qs' | |
import {env} from 'src/env' | |
import {timestamp} from './timestamp' | |
// 用于配置不同环境api地址 | |
interface IAPIURL { | |
development: string | |
test: string | |
production: string | |
} | |
export const GET = (api: string | IAPIURL) => { | |
const apiURL = typeof api === 'string' ? api : api[env] | |
return (param?: object) => { | |
const url = param | |
? `${apiURL}?${qs.stringify({...param, ts: timestamp()})}` | |
: apiURL | |
return fetch(url, { | |
headers: { | |
Accept: 'application/json' | |
}, | |
credentials: 'include' | |
}) | |
.catch(e => Promise.reject(new Error('网络错误'))) | |
.then(response => { | |
return response | |
.json() | |
.catch(e => Promise.reject(new Error('服务器错误'))) | |
.then(json => json) | |
}) | |
} | |
} | |
export const POST = (api: string, isFormData: boolean = true) => { | |
const apiURL = typeof api === 'string' ? api : api[env] | |
return (param: object) => { | |
return fetch(apiURL, { | |
method: 'POST', | |
credentials: 'include', | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': isFormData | |
? 'application/x-www-form-urlencoded' | |
: 'application/json; charset=utf-8' | |
}, | |
body: isFormData ? qs.stringify(param) : JSON.stringify(param) | |
}) | |
.catch(e => Promise.reject(new Error('网络错误'))) | |
.then(response => { | |
return response | |
.json() | |
.catch(e => Promise.reject(new Error('服务器错误'))) | |
.then(json => json) | |
}) | |
} | |
} | |
export default {GET, POST} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
don't use fetch, use axios