|
@@ -14,7 +14,6 @@ function getHeaders(headers, body) {
|
|
|
return headers
|
|
|
}
|
|
|
|
|
|
-
|
|
|
function request_get(url, headers) {
|
|
|
return new Promise((resolve, reject) => {
|
|
|
var callback = function (res) {
|
|
@@ -47,6 +46,53 @@ function request_get(url, headers) {
|
|
|
} else {
|
|
|
httpsReq = https.request(url, options, callback).on('error', errorback);
|
|
|
}
|
|
|
+
|
|
|
+ // 不要忘了关闭请求,以防止内存泄漏
|
|
|
+ httpsReq.end();
|
|
|
+ });
|
|
|
+}
|
|
|
+
|
|
|
+function request_get_timeout(url, headers) {
|
|
|
+ return new Promise((resolve, reject) => {
|
|
|
+ var callback = function (res) {
|
|
|
+ let data = '';
|
|
|
+
|
|
|
+ // 监听数据事件来收集响应数据
|
|
|
+ res.on('data', (chunk) => {
|
|
|
+ data += chunk;
|
|
|
+ });
|
|
|
+
|
|
|
+ // 监听结束事件来处理响应结束
|
|
|
+ res.on('end', () => {
|
|
|
+ clearTimeout(timeout); // 清除超时定时器
|
|
|
+ // logger.info(`响应体: ${data}`);
|
|
|
+ resolve(data);
|
|
|
+ });
|
|
|
+ }
|
|
|
+ var errorback = function errorback(e) {
|
|
|
+ clearTimeout(timeout); // 清除超时定时器
|
|
|
+ // logger.error(`请求遇到问题: ${e.message}`);
|
|
|
+ reject(e);
|
|
|
+ }
|
|
|
+ // 请求的选项
|
|
|
+ const options = {
|
|
|
+ method: 'GET',
|
|
|
+ headers: getHeaders(headers, "")
|
|
|
+ };
|
|
|
+
|
|
|
+ let httpsReq = null
|
|
|
+ if (!url.includes("https")) {
|
|
|
+ httpsReq = http.request(url, options, callback).on('error', errorback);
|
|
|
+ } else {
|
|
|
+ httpsReq = https.request(url, options, callback).on('error', errorback);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 设置超时限制为2秒
|
|
|
+ const timeout = setTimeout(() => {
|
|
|
+ httpsReq.abort(); // 中止请求
|
|
|
+ reject(new Error('请求超时')); // 拒绝 Promise
|
|
|
+ }, 2000); // 2000 毫秒即2秒
|
|
|
+
|
|
|
// 不要忘了关闭请求,以防止内存泄漏
|
|
|
httpsReq.end();
|
|
|
});
|
|
@@ -143,6 +189,7 @@ function dowFile(url, fileName, dowPath, headers) {
|
|
|
}
|
|
|
|
|
|
module.exports = {
|
|
|
+ request_get_timeout,
|
|
|
request_get,
|
|
|
request_post,
|
|
|
dowFile,
|