MCPcopy Index your code
hub / github.com/xerrors/Yuxi / apiRequest

Function apiRequest

web/src/apis/base.js:17–140  ·  view source on GitHub ↗
(url, options = {}, requiresAuth = true, responseType = 'json')

Source from the content-addressed store, hash-verified

15 * @returns {Promise} - 请求结果
16 */
17export async function apiRequest(url, options = {}, requiresAuth = true, responseType = 'json') {
18 try {
19 const isFormData = options?.body instanceof FormData
20 // 默认请求配置
21 const requestOptions = {
22 ...options,
23 headers: {
24 ...(!isFormData ? { 'Content-Type': 'application/json' } : {}),
25 ...options.headers
26 }
27 }
28
29 // 如果需要认证,添加认证头
30 if (requiresAuth) {
31 const userStore = useUserStore()
32 if (!userStore.isLoggedIn) {
33 throw new Error('用户未登录')
34 }
35
36 Object.assign(requestOptions.headers, userStore.getAuthHeaders())
37 }
38
39 // 发送请求
40 const response = await fetch(url, requestOptions)
41
42 // 处理API返回的错误
43 if (!response.ok) {
44 // 尝试解析错误信息
45 let errorMessage = `请求失败: ${response.status}, ${response.statusText}`
46 let errorData = null
47
48 console.log('API请求失败:', {
49 url,
50 status: response.status,
51 statusText: response.statusText,
52 headers: Object.fromEntries(response.headers.entries())
53 })
54
55 try {
56 errorData = await response.json()
57 errorMessage = errorData.detail || errorData.message || errorMessage
58 console.log('API错误详情:', errorData)
59
60 // 如果是422错误,打印更详细的信息
61 if (response.status === 422) {
62 console.error('422验证错误详情:', {
63 url,
64 requestMethod: requestOptions.method,
65 requestHeaders: requestOptions.headers,
66 requestBody: requestOptions.body,
67 responseData: errorData
68 })
69 }
70 } catch (e) {
71 // 如果无法解析JSON,使用默认错误信息
72 console.log('无法解析错误响应JSON:', e)
73 }
74

Callers 6

knowledge_api.jsFile · 0.90
agent_api.jsFile · 0.90
apiGetFunction · 0.85
apiPostFunction · 0.85
apiPutFunction · 0.85
apiDeleteFunction · 0.85

Calls 2

jsonMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected