diff --git a/lib/plugins/event_dispatcher/index.node.ts b/lib/plugins/event_dispatcher/index.node.ts index f9f716caf..8efd7fb4f 100644 --- a/lib/plugins/event_dispatcher/index.node.ts +++ b/lib/plugins/event_dispatcher/index.node.ts @@ -1,5 +1,5 @@ /** - * Copyright 2016-2018, 2020-2021, Optimizely + * Copyright 2016-2018, 2020-2021, 2024 Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,19 +51,26 @@ export const dispatchEvent = function( }, }; + const reqWrapper: { req?: http.ClientRequest } = {}; + const requestCallback = function(response?: { statusCode: number }): void { if (response && response.statusCode && response.statusCode >= 200 && response.statusCode < 400) { callback(response); } + reqWrapper.req?.destroy(); + reqWrapper.req = undefined; }; - const req = (parsedUrl.protocol === 'http:' ? http : https) + reqWrapper.req = (parsedUrl.protocol === 'http:' ? http : https) .request(requestOptions, requestCallback as (res: http.IncomingMessage) => void); // Add no-op error listener to prevent this from throwing - req.on('error', function() {}); - req.write(dataString); - req.end(); - return req; + reqWrapper.req.on('error', function() { + reqWrapper.req?.destroy(); + reqWrapper.req = undefined; + }); + reqWrapper.req.write(dataString); + reqWrapper.req.end(); + return reqWrapper.req; }; export default {