(url: string, options: any = {})
| 478 | method, |
| 479 | headers: { |
| 480 | "Content-Type": "application/json", |
| 481 | "User-Agent": "TeleBox/1.0", |
| 482 | ...headers, |
| 483 | }, |
| 484 | timeout, |
| 485 | }, |
| 486 | (res: any) => { |
| 487 | res.setEncoding("utf8"); |
| 488 | let body = ""; |
| 489 | let dataLength = 0; |
| 490 | const maxResponseSize = 10 * 1024 * 1024; |
| 491 | |
| 492 | res.on("data", (chunk: string) => { |
| 493 | dataLength += chunk.length; |
| 494 | if (dataLength > maxResponseSize) { |
| 495 | req.destroy(); |
| 496 | reject(new Error("响应数据过大")); |
| 497 | return; |
| 498 | } |
| 499 | body += chunk; |
| 500 | }); |
| 501 | |
| 502 | res.on("end", () => { |
| 503 | try { |
| 504 | const cleanBody = HttpClient.cleanResponseText(body); |
| 505 | const parsedData = cleanBody ? JSON.parse(cleanBody) : {}; |
| 506 | resolve({ |
| 507 | status: res.statusCode || 0, |
| 508 | data: parsedData, |
| 509 | headers: res.headers, |
| 510 | }); |
| 511 | } catch (error) { |
| 512 | resolve({ |
| 513 | status: res.statusCode || 0, |
| 514 | data: HttpClient.cleanResponseText(body), |
| 515 | headers: res.headers, |
| 516 | }); |
| 517 | } |
| 518 | }); |
| 519 | } |
| 520 | ); |
| 521 | |
| 522 | req.on("error", (error: any) => { |
| 523 | reject(new Error(`网络请求失败: ${error.message}`)); |
| 524 | }); |
| 525 | |
| 526 | req.on("timeout", () => { |
| 527 | req.destroy(); |
| 528 | reject(new Error("请求超时")); |
| 529 | }); |
| 530 | |
| 531 | if (data) { |
| 532 | if (typeof data === "object") { |
| 533 | const jsonData = JSON.stringify(data); |
| 534 | req.write(jsonData); |
| 535 | } else if (typeof data === "string") { |
| 536 | req.write(data); |
| 537 | } |
no test coverage detected