(origin, path, options = {})
| 78 | } |
| 79 | |
| 80 | async function requestJson(origin, path, options = {}) { |
| 81 | throwIfStopped(); |
| 82 | const { |
| 83 | method = 'GET', |
| 84 | token = '', |
| 85 | body = undefined, |
| 86 | } = options; |
| 87 | |
| 88 | const response = await fetch(`${origin}${path}`, { |
| 89 | method, |
| 90 | credentials: 'same-origin', |
| 91 | headers: { |
| 92 | 'Content-Type': 'application/json', |
| 93 | ...(token ? { Authorization: `Bearer ${token}` } : {}), |
| 94 | }, |
| 95 | body: body === undefined ? undefined : JSON.stringify(body), |
| 96 | }); |
| 97 | |
| 98 | const text = await response.text(); |
| 99 | let json = null; |
| 100 | try { |
| 101 | json = text ? JSON.parse(text) : null; |
| 102 | } catch { |
| 103 | json = null; |
| 104 | } |
| 105 | |
| 106 | if (json && typeof json === 'object' && 'code' in json) { |
| 107 | if (json.code === 0) { |
| 108 | return json.data; |
| 109 | } |
| 110 | throw new Error(json.message || json.detail || `请求失败(${path})`); |
| 111 | } |
| 112 | |
| 113 | if (!response.ok) { |
| 114 | throw new Error((json && (json.message || json.detail)) || `请求失败(HTTP ${response.status}):${path}`); |
| 115 | } |
| 116 | |
| 117 | return json; |
| 118 | } |
| 119 | |
| 120 | function storeAuthSession(loginData) { |
| 121 | if (!loginData?.access_token) { |
no test coverage detected