electron: End event of net.request Response is never emitted

  • Electron version: 2.0.0-beta.6
  • Operating system: Windows 10

Expected behavior

HTTP Response should emit “end” event to let the application know that the entire body was received.

Actual behavior

I can see that data is received and actually on this very specific call the whole reponse body is passed to the data callback at once, but i cannot assume that this will always be the case. So i sort of rely on the “end” event.

How to reproduce

Im follwong this example: https://github.com/electron/electron/blob/master/docs/api/net.md#net

Im trying to use the net package (from the rendering process) via the remote interface to make a REST call to a webservice, like so:


const net = require("electron").remote.net;
const requestOptions = {
     auth: "myuser:mypwd", 
     url: "https://my.rest.service/oauth/token", 
     method: "POST"
};

const request = net.request(requestOptions);
request.on("response", function(response) {
     console.log(response.statusCode);

     response.on("data", function(data) {
          console.log("data: " data);
     });
     response.on("end", function {
          // will never get called
          console.log("end");
     });
});
request.end();

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 1
  • Comments: 18 (5 by maintainers)

Most upvoted comments

I solved by moving the “end” event definition before “date” event.

This just cost me and a teammate 3 or so man-hours. Would it be possible to update the docs to inform developers about this hazard?

in my case, move the “end” event before the “date” event is ok, but why?

            let data = '';
            response.on('end', () => {
                console.log(response.statusCode);
                console.log(data);
            });
            response.on("data", chunk => {
                data += chunk;
            });

but not if the status code is > 400 …

Same issue when using electron 6.1.5, response event never emitted when using net.request in renderer process and status code > 400

@martyglaubitz verdict is that emitting the response event is async, so by the time it hits the renderer and you want to hook the data and end events they’ve already happened.

data works because it’s a race condition, and if you had a large enough file you were loading the end event would likely work too. Sadly, fixing this would involve a lot of nasty workarounds and hacks that aren’t in our best interest to implement so i’d say keep it in your main process.

Good luck, and sorry about that!

@codebytere alright thanks! Guess i’ll just offload the operation into the main process till it’s fixed 😃