| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import { BASE_URL, TIMEOUT, DEFAULT_HEADERS } from './config'
- const request = (options = {}) => {
- return new Promise((resolve, reject) => {
- const token = uni.getStorageSync('token') || ''
- const method = (options.method || 'GET').toUpperCase()
- const useParams = method === 'GET' || method === 'DELETE'
- const requestData = useParams ? (options.params || options.data || {}) : (options.data || {})
-
- uni.request({
- url: BASE_URL + options.url,
- method: method,
- data: requestData,
- header: {
- ...DEFAULT_HEADERS,
- 'Content-Type': 'application/json',
- 'Authorization': token ? `Bearer ${token}` : '',
- ...options.header
- },
- timeout: TIMEOUT,
- success: (res) => {
- if (res.statusCode !== 200) {
- uni.showToast({ title: '网络请求异常', icon: 'none' })
- return reject(res)
- }
- const { code, msg, data, total, rows } = res.data
- if (code === 200) {
- resolve(rows !== undefined ? { total, rows } : data)
- } else if (code === 401) {
- uni.removeStorageSync('token')
- uni.reLaunch({ url: '/pages/login/index' })
- reject(res.msg)
- } else {
- uni.showToast({ title: msg || '操作失败', icon: 'none' })
- reject(res.msg)
- }
- },
- fail: (err) => {
- uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
- reject(err)
- }
- })
- })
- }
- export { request }
|