starmusic-mobile
1/**
2 * HTTP 请求封装(迁移自 lx-music-mobile/src/utils/request.js)
3 * 基于 uni.request,兼容 H5 与 App
4 */
5
6const defaultHeaders = {
7 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
8}
9
10/** 处理请求数据(form / formData / json body) */
11const handleRequestData = (url, options = {}) => {
12 const { method = 'get', headers = {}, format = 'json', ...rest } = options
13 const newHeaders = Object.assign({ Accept: 'application/json' }, headers)
14 let data = rest.body
15 delete rest.body
16
17 if (method.toLocaleLowerCase() === 'post' && !newHeaders['Content-Type']) {
18 if (rest.form) {
19 newHeaders['Content-Type'] = 'application/x-www-form-urlencoded'
20 const formBody = []
21 for (const [key, value] of Object.entries(rest.form)) {
22 formBody.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
23 }
24 data = formBody.join('&')
25 delete rest.form
26 } else if (rest.formData) {
27 newHeaders['Content-Type'] = 'multipart/form-data'
28 data = rest.formData
29 delete rest.formData
30 } else {
31 newHeaders['Content-Type'] = 'application/json'
32 }
33 }
34 if (newHeaders['Content-Type'] === 'application/json' && data && typeof data !== 'string') {
35 data = JSON.stringify(data)
36 }
37 if (data === undefined) data = ''
38 return { method, headers: Object.assign({}, defaultHeaders, newHeaders), data, ...rest }
39}
40
41/**
42 * 请求方法
43 * @param {string} url
44 * @param {object} options { method, headers, body, form, formData, timeout, binary }
45 * @returns {{ promise: Promise, cancelHttp: Function }}
46 */
47export const httpFetch = (url, options = { method: 'get' }) => {
48 const requestObj = fetchData(url, options)
49 return {
50 promise: requestObj.request.catch((err) => {
51 console.log('[httpFetch error]', url, err)
52 throw err
53 }),
54 cancelHttp() {
55 requestObj.abort()
56 },
57 }
58}
59
60/** http get(回调风格) */
61export const httpGet = (url, options, callback) => {
62 if (typeof options === 'function') {
63 callback = options
64 options = {}
65 }
66 const requestObj = fetchData(url, { ...options, method: 'get' })
67 requestObj.request
68 .then((resp) => {
69 callback(null, resp, resp.body)
70 })
71 .catch((err) => {
72 callback(err, null, null)
73 })
74 return () => {
75 requestObj.abort()
76 }
77}
78
79const fetchData = (url, { timeout = 15000, ...options }) => {
80 const controller = typeof AbortController !== 'undefined' ? new AbortController() : null
81 let timer = null
82
83 const request = new Promise((resolve, reject) => {
84 if (controller) {
85 timer = setTimeout(() => {
86 timer = null
87 controller.abort()
88 }, timeout)
89 }
90
91 const { method, headers, data, binary } = handleRequestData(url, { timeout, ...options })
92
93 uni.request({
94 url,
95 method: method.toUpperCase(),
96 data,
97 header: headers,
98 timeout: Math.min(timeout, 60000),
99 responseType: binary ? 'arraybuffer' : 'text',
100 success: (res) => {
101 let body = res.data
102 if (binary && body instanceof ArrayBuffer) {
103 body = new Uint8Array(body)
104 } else if (!binary && typeof body === 'string') {
105 try {
106 body = JSON.parse(body)
107 } catch (e) {
108 // 保持字符串
109 }
110 }
111 resolve({
112 headers: res.header || {},
113 body,
114 statusCode: res.statusCode,
115 statusMessage: '',
116 url: res.url || url,
117 ok: res.statusCode >= 200 && res.statusCode < 300,
118 })
119 },
120 fail: (err) => {
121 const error = new Error(err.errMsg || 'Network request failed')
122 if (controller && err.errMsg && /abort/i.test(String(err.errMsg))) {
123 error.message = 'Aborted'
124 }
125 reject(error)
126 },
127 complete: () => {
128 if (timer) {
129 clearTimeout(timer)
130 timer = null
131 }
132 },
133 })
134 })
135
136 return {
137 request,
138 abort() {
139 if (controller) controller.abort()
140 },
141 }
142}
143
144/** URL 可访问性检查 */
145export const checkUrl = async (url, options = {}) => {
146 return fetchData(url, { method: 'head', ...options }).request.then((resp) => {
147 if (resp.statusCode === 200) return Promise.resolve()
148 throw new Error(resp.statusCode)
149 })
150}