(url: string, options: HttpRequestOptions = {})
| 27 | * 默认禁用缓存,确保每次都获取最新数据 |
| 28 | */ |
| 29 | export function httpRequest(url: string, options: HttpRequestOptions = {}): Promise<HttpResponse> { |
| 30 | return new Promise((resolve, reject) => { |
| 31 | const { |
| 32 | method = 'GET', |
| 33 | headers = {}, |
| 34 | body, |
| 35 | validateStatus = (status) => status >= 200 && status < 300 |
| 36 | } = options |
| 37 | |
| 38 | // 默认禁用缓存的请求头(用户传入的 headers 可以覆盖) |
| 39 | const defaultHeaders = { |
| 40 | 'Cache-Control': 'no-cache, no-store, must-revalidate', |
| 41 | Pragma: 'no-cache', |
| 42 | Expires: '0', |
| 43 | ...headers // 用户自定义的 headers 会覆盖默认值 |
| 44 | } |
| 45 | |
| 46 | const finalUrl = url |
| 47 | |
| 48 | const makeRequest = (requestUrl: string): void => { |
| 49 | const request = net.request({ |
| 50 | method, |
| 51 | url: requestUrl, |
| 52 | redirect: 'follow', // 自动跟随重定向(manual 模式在某些 Electron 版本会导致 Redirect was cancelled 错误) |
| 53 | session: session.defaultSession // 显式指定使用 defaultSession(确保代理配置生效) |
| 54 | }) |
| 55 | |
| 56 | // 设置请求头(包含默认的禁用缓存头) |
| 57 | Object.entries(defaultHeaders).forEach(([key, value]) => { |
| 58 | request.setHeader(key, value) |
| 59 | }) |
| 60 | |
| 61 | // 处理响应 |
| 62 | request.on('response', (response: IncomingMessage) => { |
| 63 | const chunks: Buffer[] = [] |
| 64 | const responseHeaders: Record<string, string | string[]> = {} |
| 65 | |
| 66 | // 收集响应头 |
| 67 | Object.entries(response.headers).forEach(([key, value]) => { |
| 68 | responseHeaders[key] = value |
| 69 | }) |
| 70 | |
| 71 | // 收集响应数据 |
| 72 | response.on('data', (chunk: Buffer) => { |
| 73 | chunks.push(chunk) |
| 74 | }) |
| 75 | |
| 76 | response.on('end', () => { |
| 77 | const buffer = Buffer.concat(chunks) |
| 78 | let data: any |
| 79 | |
| 80 | // 根据 Content-Type 解析数据 |
| 81 | const contentType = response.headers['content-type'] |
| 82 | const contentTypeStr = Array.isArray(contentType) ? contentType[0] : contentType |
| 83 | |
| 84 | if (contentTypeStr?.includes('application/json')) { |
| 85 | try { |
| 86 | data = JSON.parse(buffer.toString('utf-8')) |
no test coverage detected