Skip to content

Instantly share code, notes, and snippets.

@ibreathebsb
Created September 26, 2018 10:12
Show Gist options
  • Save ibreathebsb/c8973529e8dea292c9489bdc76627e8f to your computer and use it in GitHub Desktop.
Save ibreathebsb/c8973529e8dea292c9489bdc76627e8f to your computer and use it in GitHub Desktop.
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}
@ibreathebsb
Copy link
Author

don't use fetch, use axios

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment