const axios = require('axios'); const axiosRetry = require('axios-retry').default; const {HttpsProxyAgent} = require("https-proxy-agent"); class HttpClient { constructor(options = {}) { this.client = axios.create({ timeout: options.timeout || 5000, headers: options.headers || {}, validateStatus: function (status) { return status >= 200 && status < 300; } }); this.setupRetry(); } setupRetry() { axiosRetry(this.client, { retries: 3, retryDelay: (retryCount) => { return retryCount * 1000; }, retryCondition: (error) => { return axiosRetry.isNetworkOrIdempotentRequestError(error) || error.code === 'ECONNRESET'; } }); } // POST 方法 async post(url, data = {}, config = {}) { try { const response = await this.client.post(url, data, { headers: { 'Content-Type': 'application/json', ...config.headers }, ...config }); return response.data; } catch (error) { this.handleError(error); throw error; } } // POST 表单数据 async postForm(url, formData, config = {}) { try { const response = await this.client.post(url, formData, { headers: { 'Content-Type': 'multipart/form-data', ...config.headers }, ...config }); return response.data; } catch (error) { this.handleError(error); throw error; } } async request(url, options = {}) { try { const response = await this.client.request({ url, ...options }); return response.data; } catch (error) { this.handleError(error); throw error; } } // POST 方法 async otherPost(options,data) { try { const response = await this.client.post(options.url, data, { headers:options.headers }); return response.data; } catch (error) { this.handleError(error); throw error; } } async proxyRequest(options){ try{ let tunnelHost = 'd528.kdltps.com' let tunnelPort = '15818' // 配置用户名和密码 let username = 't13322192973984' let password = '7ntreedr' return await axios({ url: options.url, method: "post", headers: options.headers, httpAgent: new HttpsProxyAgent(`http://${username}:${password}@${tunnelHost}:${tunnelPort}`), httpsAgent: new HttpsProxyAgent(`http://${username}:${password}@${tunnelHost}:${tunnelPort}`), }).then( res => { return res.data } ).catch(err => { console.log(err); }) }catch(error){ this.handleError(error); throw error; } } handleError(error) { if (error.code === 'ECONNRESET') { console.error('连接被重置'); } else if (error.code === 'ETIMEDOUT') { console.error('请求超时'); } else if (error.response) { console.error(`服务器响应错误: ${error.response.status}`); } else if (error.request) { console.error('未收到响应'); } else { console.error('请求配置错误'); } } } module.exports = HttpClient;